Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

reactjs - Fetching JSON returns error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and status code 304: Not Modified

I am trying to fetch a JSON file but it returns the errors Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and 304: Not Modified. I tried to add headers 'Content-Type': 'application/json and 'Accept': 'application/json' but then it returns error 404: Not found.

Here is the code where I am fetching my 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>
    )
  }
}

Here is my json file:

{
    "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"
    ]
}

I also at one point tried to use response.text() instead of json() but it returned my index.html file.

I have been looking around the web for the past week trying to find a solution but what worked for others didn't work for me. Any advice?

EDIT: When I did console.log(response.headers.get('Content-Type')) it returned text/html; charset=UTF-8. Shouldn't it already be application/json? Why is the initial encoding 'text/html'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check Whether You have the .env file with REACT_APP_API_URL=http://localhost:3001 in it. The file should be in the root folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...