提取操作会在JSON中提供响应意外令牌<

时间:2018-10-25 14:43:10

标签: reactjs

如何获取本地json。错误显示Unexpected token < ..。我没有网络错误。

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)
    })
  }
}

下面是我在开发工具中得到的答复

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

尽管响应为200,但出现以下错误:

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

项目结构:

|---static
|   |---reactApp
|       |--components
|       |  |--items.json
|       |  |--Itemslist.js
|       |
|       |--App.js

1 个答案:

答案 0 :(得分:3)

Unexpected token < ..表示JSON解析失败,因为您期望JSON时以某种方式获取HTML。请检查http://localhost:5000/items.json的响应是否确实是有效的JSON。

一种简单的检查方法是将代码更改为res.text()并将结果记录到控制台。

相关问题