【问题标题】:Unexpected end of input when using fetch API in react [duplicate]在反应中使用 fetch API 时输入意外结束 [重复]
【发布时间】:2019-10-19 00:49:17
【问题描述】:

我正在使用 fetch 来简单地从虚拟 api 端点获取数据,但是当我在 fetch 函数中添加配置时,我得到了一个意外的输入结束错误。

这很好用,控制台记录了一个包含 200 个项目的数组

componentDidMount() {
    let url = 'https://jsonplaceholder.typicode.com/todos';
    let config =  {
      method: "GET",
      mode: "no-cors",
      headers: {
        "access-control-allow-origin" : "*",
        "Content-type": "application/json; charset=UTF-8",
        "access-control-allow-headers": "content-type"
      }
    };


    fetch(url)
      .then(res => res.json())
      .then(data => this.setState({ data, }))

}

但是当我将配置作为参数添加时,它会显示并出错。

componentDidMount() {
    let url = 'https://jsonplaceholder.typicode.com/todos';
    let config =  {
      method: "GET",
      mode: "no-cors",
      headers: {
        "access-control-allow-origin" : "*",
        "Content-type": "application/json; charset=UTF-8",
        "access-control-allow-headers": "content-type"
      }
    };


    fetch(url, config)   // This is where the error occurs
      .then(res => res.json())
      .then(data => this.setState({ data, }))

}

错误:

Dashboard.jsx:35 Uncaught (in promise) SyntaxError: Unexpected end of input
    at Dashboard.jsx:35

和

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://jsonplaceholder.typicode.com/todos with MIME type application/json.

【问题讨论】:

  • 为什么要从客户端获取 API 发送 access-control-allow-origin (CORS) 标头。这些应该从服务器发送以避免跨域问题。删除 access-control-allow-headers 和 access-control-allow-origin 标头。这是工作code sandbox link

标签: javascript reactjs cors fetch


【解决方案1】:

首先将mode: 'no-cors' 更改为mode: 'cors'

关于 CORS 问题

您需要更新您尝试从中请求信息的服务器上的 CORS 标头。这些 CORS 政策是出于安全目的而制定的

如果您可以访问它,请添加此标头:

'Access-Control-Allow-Origin: *'

或

'Access-Control-Allow-Origin: http://example.com'

【讨论】:

  • 我实际上正在构建一个电子应用程序,在浏览器上禁用 cors 没有帮助,而且我已经包含了您建议的上述标题,但仍然出现 CORS 错误!
  • @GaganGanapathySudhirAjjikut 仔细阅读我的回答,如果您有权访问,则需要将标头添加到服务器端
猜你喜欢
  • 2018-12-31
  • 2018-01-23
  • 1970-01-01
  • 2018-05-07
  • 2017-11-23
  • 2018-10-03
  • 2020-07-29
  • 2016-10-26
  • 2019-01-17
相关资源
最近更新 更多