如何解决如何在反应中从 api 获取数据?
我想在响应中从我的 API 中获取数据:
async componentDidMount(){
const url="https://covidensa.herokuapp.com/";
const response =await fetch(url);
const data=await response.json();
this.setState({ person:data.results,loading:false });
console.log(this.state.person)
console.log(this.state.option.option1.option2)
console.log(data.results)
}
从源“http://localhost:3000”获取“https://covidensa.herokuapp.com/”的访问权限已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
Area Chart.js:36 GET https://covidensa.herokuapp.com/ net::ERR_Failed
解决方法
您没有从 api 获取任何数据的原因是 CORS 阻止了它。 Cors 代表跨域资源共享,它基本上起到了阻止脚本等潜在恶意代码的安全作用...
以下内容来自 Mozilla 文档:
@api.constrains('sale_lines')
def _check_sale_lines(self):
for record in self:
if len(record.sale_lines) > 2:
raise ValidationError('Not more than 2 lines ')
注意你只有
const response = await fetch(url,{
method: 'POST',// *GET,POST,PUT,DELETE,etc.
mode: 'cors',// no-cors,*cors,same-origin
cache: 'no-cache',// *default,no-cache,reload,force-cache,only-if-cached
credentials: 'same-origin',// include,*same-origin,omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',},redirect: 'follow',// manual,*follow,error
referrerPolicy: 'no-referrer',// no-referrer,*no-referrer-when-downgrade,origin,origin-when-cross-origin,same-origin,strict-origin,strict-origin-when-cross-origin,unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
如错误消息中所述,您将需要添加模式为“no-cors”的参数。
,请在您的后端使用 cors。如果您使用 Nodejs 作为服务器,请执行 this.authService.fireIsLoggedIn.subscribe(res=>{...})
,然后导入您的代码并编写 npm install cors
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。