已通过使用 axios 和 fetch in react 被 CORS 策略阻止 [英] has been blocked by CORS policy by using axios and fetch in react
本文介绍了已通过使用 axios 和 fetch in react 被 CORS 策略阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对服务器进行 post 请求,但在 React 中使用 axios 和 fetch 不断收到 CORS 错误.
I'm trying to do a post request of a server but keep getting a CORS error using axios and fetch in React.
代码:
fetch('https://api/entries',
{ mode: 'no-cors',
method: 'post',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
body: JSON.stringify({
"KEY":"VALUE"
})
})
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
或
axios({
method: 'post',
url: 'https://api/entries',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
axios 控制台响应
axios console response
Access to XMLHttpRequest at 'https://api/entries' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
另一个
获取控制台响应
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api/entries with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
谢谢
推荐答案
解决这个问题最好和最简单的方法是使用代理 URL.
The best and easiest way is to tackle this problem is to use Proxy URL.
像这样
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios.post(PROXY_URL+URL)
.then( i => console.log(i) )
.catch(e => console.error( "Error occured! ", e));
在您的情况下,请尝试像这样使用它:这应该可以工作.
in your case try using this like this: This should work.
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios({
method: 'post',
url: PROXY_URL+URL,
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
您甚至可以通过 fetch()
这篇关于已通过使用 axios 和 fetch in react 被 CORS 策略阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文