在React中使用Fetch API时输入意外结束

时间:2019-06-03 12:52:32

标签: javascript reactjs cors 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.

1 个答案:

答案 0 :(得分:0)

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

关于CORS问题

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

如果有权访问,请添加以下标头:

'Access-Control-Allow-Origin: *'

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