获取 JSON 返回错误 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and status code 304: Not Modified

kri*_*yip 7 json reactjs

我正在尝试获取一个 JSON 文件,但它返回错误Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and 304: Not Modified。我尝试添加标题'Content-Type': 'application/json'Accept': 'application/json'但随后返回错误404:未找到

这是我获取 JSON 的代码:

import React from 'react';

export default class LabExperiment extends React.Component {

componentWillMount() {
    const readmePath = require("./docs/iat/iatDependency.json");

    fetch("./docs/iat/iatDependency.json")
    .then(response => {
        response.json();
    })
    .then(text => {
        console.log(text);
    });
}

render() {
    return(
        <div>Hello</div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 json 文件:

{
    "js": [
        "../jsPsych/jspsych.js",
        "../jsPsych/plugins/jspsych-iat-image.js",
        "../jsPsych/plugins/jspsych-iat-html.js",
        "../jsPsych/plugins/jspsych-html-keyboard-response.js"
    ],
    "css": [
        "../jsPsych/css/jspsych.css"
    ]
}
Run Code Online (Sandbox Code Playgroud)

我也曾一度尝试使用response.text()而不是json()但它返回了我的 index.html 文件。

过去一周我一直在网上寻找解决方案,但对其他人有用的方法对我不起作用。有什么建议吗?

编辑:当我这样做时,console.log(response.headers.get('Content-Type'))它返回了text/html; charset=UTF-8. 不应该是 application/json 吗?为什么初始编码是“text/html”?

an0*_*0us -2

我想你可能正在使用create-react-app. 如 中所示create-react-appwebpack-dev-server用于处理请求,并为每个请求提供服务index.html。所以你得到了

JSON 中位置 0 和状态代码 304 处出现意外标记 <:未修改

因此,要解决这个问题,您可以执行以下操作:

  1. 跑步npm run eject

config之后,在应用程序的根目录下创建该文件夹。

  1. config/webpackDevServer.config.js

  2. 然后我们需要设置disableDotRule: false进去webpackDevServer.config.js

        historyApiFallback: {
         // previously disableDotRule: true,
         disableDotRule: false,
        },
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将您的 json 文件保留docs/iat/iatDependency.jsonpublic文件夹中。

  4. 使用fetch('/docs/iat/iatDependency.json').then(res => res.json()).then(data => console.log('data', data))