gpt4 book ai didi

javascript - 使用 fetch API 的 CORS 错误 - react 创建应用程序

转载 作者:行者123 更新时间:2023-12-03 07:20:49 25 4
gpt4 key购买 nike

我正在使用 fetch 使用 API,但出现 CORS 错误。
我尝试了多个标题,但我不明白有什么问题。

我不是 API 的所有者,所以我无法更改它,但检查它返回的响应 access-control-allow-origin .

以下是我的请求方法:

export const execPOST = (url, body) => {
return fetch(url, {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
};

回应是:
Request URL: http://api
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: ip
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: *

上面的响应还不足以允许我的请求吗?

控制台错误:

OPTIONS http://api net::ERR_ABORTED 405 (Method Not Allowed) Access to fetch at 'http://api' 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.



我使用 "https://cors-anywhere.herokuapp.com/" 得到了这个工作(同时我正在开发) ,但我认为我不应该将它用于生产环境。

我发现了很多关于这个问题的 Material ,但是除了实现一个后端来发出请求或使用其他东西作为代理来发出请求等等之外,没有任何其他的工作......

最佳答案

更新代码如下(使用 'mode' 和值 'no-cors' ):
更多详情请点击链接 => https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

export const execPOST = (url: string, body: any) => {
return fetch(url, {
mode: 'no-cors',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
};

关于javascript - 使用 fetch API 的 CORS 错误 - react 创建应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56067550/

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