gpt4 book ai didi

xmlhttprequest - 在react中使用axios和fetch已被CORS策略阻止

转载 作者:行者123 更新时间:2023-12-02 20:26:10 26 4
gpt4 key购买 nike

我正在尝试对服务器执行 post 请求,但在 React 中使用 axios 和 fetch 时不断收到 CORS 错误。

代码:

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 控制台响应

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

像这样

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

在你的情况下尝试这样使用:这应该有效。

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

您甚至可以将代理 URL 与 fetch() 一起使用

关于xmlhttprequest - 在react中使用axios和fetch已被CORS策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55846429/

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