我正在尝试获取一个JSON文件,但它返回错误未被修改的SyntaxError:位置为0的JSON中的意外令牌<,以及304: NotModied。我试图添加headers、'Content-Type': 'application/json和'Accept': 'application/json',但随后它返回错误404: NotFind。
下面是我获取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>
)
}
}这是我的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"
]
}我还曾经尝试使用response.text()而不是json(),但它返回了我的index.html文件。
在过去的一周里,我一直在网络上寻找解决方案,但是对别人有用的东西对我却没有用。有什么建议吗?
编辑:当我做console.log(response.headers.get('Content-Type'))时,它返回了text/html; charset=UTF-8。不应该已经是应用程序/json了吗?为什么初始编码'text/html'?
发布于 2020-04-23 17:57:46
检查.env文件中是否包含REACT_APP_API_URL=http://localhost:3001。该文件应位于根文件夹中。
发布于 2019-04-11 08:36:50
我想你可能在使用create-react-app。与create-react-app一样,webpack-dev-server用于处理请求,对于每个请求,它都为index.html提供服务。所以你要
位置0和状态代码304的JSON中的意外令牌<:未修改
因此,要解决这个问题,您可以执行以下操作:
npm run eject之后,config文件夹将在应用程序的根目录下创建。
config/webpackDevServer.config.js。disableDotRule: false中设置webpackDevServer.config.js。
historyApiFallback:{ //以前disableDotRule: true,disableDotRule: false,},docs/iat/iatDependency.json )保存在public文件夹中。fetch('/docs/iat/iatDependency.json').then(res => res.json()).then(data => console.log('data', data))https://stackoverflow.com/questions/47368716
复制相似问题