我正在 React Web 应用程序中使用 Fetch 进行 API 调用(在另一个域上运行)。我收到错误以下错误。
从源“http://localhost:3000”获取“--------API URL---------”的访问已被 CORS 策略阻止:
对预检请求的响应不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我还在 Stack Overflow 上阅读了关于同一问题的几个答案,标题为“Access-Control-Allow-Origin”,但仍然不知道如何解决这个问题。我不想在 Chrome 中使用扩展程序或使用临时黑客来解决这个问题。请提出解决上述问题的标准方法。
我的代码如下所示:
{
return fetch('-----------API URL--------',
{ method:'GET',
mode: 'cors',
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.ALLORDERSRX);
this.setState({
isLoading: false,
dataSource: responseJson.ALLORDERSRX,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
Run Code Online (Sandbox Code Playgroud)