gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:23 25 4
gpt4 key购买 nike

我对 React 很陌生,对 NodeJS 也很陌生。我正在尝试测试如何从我的 NodeJS Web 服务中提取 json 数据并在 React 中渲染它。我仅处于测试阶段,但正在努力理解这个问题是什么。我可以通过以下方式从演示作业 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));
}

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

有什么想法吗?总而言之,我真的很感激一些更广泛的 react 代码来获取作业列表,将其添加到组件状态,然后渲染列表 - 沿着以下行:

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

enter image description here

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

关于javascript - 在react.js中将no-cors包含到 header 中以获取json内容时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42342452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com