【问题标题】:React failing to parse a JSON object from serverReact 无法从服务器解析 JSON 对象
【发布时间】:2018-04-15 16:33:22
【问题描述】:

我遇到了这个错误: Uncaught (in promise) SyntaxError: Unexpected token [ in JSON at position 1 当我将包含 JSON 对象数组的 JSON 对象传递给我的组件时。对象结构为: { "arrayName": [{object},{object},{object}, etc...] }

我已经通过验证器运行了 JSON,它运行良好,但我的 api 调用总是返回相同的错误。

export const api = 'http://localhost:8000'

export const headers = {
    'Content-Type': 'application/json',
    'Accept' : 'application/json',

}

export const getAll = () =>
    fetch(`${api}/480.json`, { headers })
        .then(res => res.json())
        .then(data => data.events)

这是在 App.js 中调用它的地方:

componentDidMount() {
        eventsAPI.getAll().then((events) => {
            console.log(events)
            this.setState({ events })
        })
    }

我不确定我为什么会收到错误,我知道我正在发送一个有效的 JSON 对象,我接收它的方式是错误的吗?我可以在开发工具的网络选项卡中看到正在传递和接收正确的格式。我只是不知道我到底哪里错了。这是从服务器记录的响应。我可以在开发工具中看到 XHR 响应,但在这里发布 25 多个对象有点大。

【问题讨论】:

  • 你能贴出你如何使用getAll的代码吗?目前它没有返回任何东西
  • 您能否发布一个返回数据的示例(或屏幕截图)?
  • 错误抛出在哪一行?
  • 你可以试试不添加 Content-Type 标头吗?这对于 GET 请求是不必要的。
  • 做到了! @andy729

标签: json reactjs api


【解决方案1】:

您需要修改 getAll 才能实际返回某些内容。因为它是一个 fetch,你可以直接返回它,这将返回 promise。

export const getAll = () =>
    return fetch(`${api}/480.json`, { headers })
        .then(res => res.json())
        .then(data => data.events)

现在无论您在哪里使用getAll,请务必致电then

getAll().then(data => console.log(data))

【讨论】:

  • 我添加了调用函数的代码。
  • @MichaelPorter 查看我的回答。获取之前需要return
  • 我进行了建议的更改,但反应抛出错误。箭头函数不喜欢这种语法。感谢您的帮助,我会继续努力。
  • return 语句是不必要的。箭头函数有隐式返回
猜你喜欢
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多