繁体   English   中英

当在react.js中将no-cors插入标头以获取json内容时出现奇怪的错误

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

我是个新手,对nodeJS也很新。 我正在尝试测试如何从我的nodeJS webservices中提取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 8888-所以我了解到我需要在标头中设置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));
  } 

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

有任何想法吗? 总的来说,我真的很欣赏一些更广泛的反应代码,以获取作业列表,将其添加到组件状态,然后呈现该列表-大致如下:

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标头才能访问响应。

在此处输入图片说明

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服务的标头,以使React Fetch正常工作。 这是我向我添加的nodeJS express服务标头:

// 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);

希望这是有道理的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM