将 no-cors 包含到 header 以获取 react.js 中的 json 内容时出现奇怪错误

strange error when including no-cors into header for fetch of json content in a react.js

我对 React 很陌生,对 nodeJS 也很陌生。我正在尝试测试如何从我的 nodeJS web 服务中提取 json 数据并在反应中呈现它。 我只是在测试阶段,但正在努力了解这个问题是什么。我可以通过以下方式从演示工作 json 资源中获取内容:

let url = "http://codepen.io/jobs.json";
let iterator = fetch(url);
  iterator
    .then(response => response.json())
    .then(post => alert(post.jobs[3].company_name));
  } 

但我自己的 JSON 资源位于 http://localhost:8888 - 所以我了解到我需要在 header 中设置 no-cors 以允许跨站点资源,所以我自己的资源解释,我试过:

let url = "http://codepen.io/jobs.json";
let iterator = fetch(url, {mode: 'no-cors'});
  iterator
    .then(response => response.json())
    .then(post => alert(post.jobs[3].company_name));
  } 

但这给了我一个错误:"Uncaught (in promise) SyntaxError: Unexpected end of input"resonse.json() 行。

有什么想法吗?总而言之,我真的很感激一些更广泛的反应代码来获取工作列表,将其添加到组件状态然后呈现列表 - 沿着:

componentDidMount() {
  let url = "http://codepen.io/jobs.json";
  let iterator = fetch(url, {method: 'GET', mode: 'no-cors'});
  iterator
    .then(response => response.json())
    .then(post => alert(post.jobs[3].company_name));
} 

render() {        
    return(
        <div>
            <div>Items:</div>
            <div>{this.state.items.map etc</div>
        </div>  
    );
}

您从 codepen 获得的响应类型为:'cors' 但您提供的是 mode:no-cors,服务器需要发送所需的 CORS headers 才能访问响应.

componentDidMount() {
   let url = "https://codepen.io/jobs.json";
   let iterator = fetch(url, {method: 'GET', mode: 'cors'});
   iterator
     .then(response => {
       console.log('sss', response)
       return response.json();
     })
     .then(post => alert(post.jobs[3].company_name));
   }

render() {        
  return(
      <div>
        <div>Items:</div>
           <div>{this.state.items.map etc</div>
        </div>  
    );
}

只是为了让答案注释中的代码更清晰一些。 pOk8 确定了这个问题。用我的外行术语来说,我需要更改我的本地主机 Web 服务的 headers 以使反应提取能够工作。这是我添加到我的 nodeJS 快递服务 headers:

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

希望这是有道理的。