Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch gives response Unexpected token < in JSON

Tags:

reactjs

How can I fetch local json. the error says Unexpected token < ... I have no network error.

Itemslist.js:

import React, { Component } from 'react';


class Itemslist extends Component {
  componentDidMount() {
    fetch('items.json').then(res => {
      console.log(res)
      // return res.json()
    }).then(res => {
      console.log(res)
    })
  }
}

below is the response I get in dev tools

Response {type: "basic", url: 
"http://localhost:5000/items.json", redirected: false, status: 200, ok: true, …}
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:5000/items.json"
__proto__: Response

although the response is 200, I get the below error:

 bundle.js:30 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Project Structure:

|---static
|   |---reactApp
|       |--components
|       |  |--items.json
|       |  |--Itemslist.js
|       |
|       |--App.js
like image 724
Deke Avatar asked Dec 18 '22 20:12

Deke


1 Answers

Unexpected token < .. means JSON parsing failed because you somehow get HTML while expecting JSON. Please check the response of http://localhost:5000/items.json is really valid JSON.

An easy way to check would be to change the code to res.text() and log the result to the console.

like image 100
tungd Avatar answered Jan 29 '23 03:01

tungd