我正在 React Web 应用程序中使用 Fetch 进行 API 调用(在另一个域上运行)。我收到错误以下错误。
Access to fetch at '--------API URL---------' from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我还在 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);
});
}
最佳答案
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://api.liveconnect.in/backend/web/erpsync/get-all-orders?data=dbCode=UAT04M%7Cidx=100%7CuserId=6214%7Cres_format=1'; // site that doesn’t send Access-Control-*
fetch(proxyurl + url).then((resp) => resp.json())
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
关于javascript - React JS - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。跨源资源错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55097195/