Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

reactjs

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'?

like image 208
kristiyip Avatar asked Nov 18 '17 17:11

kristiyip


1 Answers

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.

like image 126
Akinthiya K I Avatar answered Nov 16 '22 22:11

Akinthiya K I