[英]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.