首页 > 解决方案 > 在反应中使用 fetch API 时输入意外结束

问题描述

我正在使用 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.

标签: javascriptreactjscorsfetch

解决方案


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

关于 CORS 问题

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

如果您有权访问它,请添加此标头:

'Access-Control-Allow-Origin: *'

或者

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

推荐阅读