gpt4 book ai didi

javascript - 外部 API 未处理 CORS 预检请求

转载 作者:行者123 更新时间:2023-11-28 16:59:12 24 4
gpt4 key购买 nike

我正在尝试为 getresponse.com 创建前端应用程序。它有自己的API,位于 https://api.getresponse.com 。当我尝试使用 Axios 或 Fetch 执行任何 javascript 请求表单浏览器时,出现此错误:

Access to XMLHttpRequest at 'https://api.getresponse.com/v3/accounts' from origin 'http://localhost:8080' 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.

在网络选项卡中我有:

Request URL: https://api.getresponse.com/v3/accounts
Request Method: OPTIONS
Status Code: 400 Bad Request

因此,据我所知,API 无法正确处理来自网络浏览器的“复杂”请求。

现在我只有一个想法 - 制作一些中间件,它将我的请求代理到 API 端点,而无需任何预检请求。

我说得对吗?我找不到此类中间件的任何示例。我在哪里可以找到任何信息?

最佳答案

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.

有关预检请求的更多详细信息,请参阅 here.

您可能应该研究一下如何处理 Content Security Policy在您的服务器上。您从 JavaScript 发出的所有请求都将由浏览器验证。因此,您的服务器应使用 header Access-Control-Allow-Origin 进行响应,了解有关 header here 的更多信息。

通过从浏览器网络选项卡进行检查,您应该能够查看响应中存在的 header 。

由于您无法控制 API 服务器,因此您可以创建 proxy server与外部服务器进行通信。详细可以找tutorial here .

这是一个 nginx 虚拟主机配置示例,它处理使用 /apihttps://api.example.com 的所有请求的代理

server {
listen 80;
server_name example.com; # Your server domain, in your case localhost
location /api {
access_log off;
proxy_pass https://api.example.com; # <--- this will the target domain
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

因此,如果您创建http://example.com/api/v3/accounts,这将被转发到https://api.example.com/api/v3/帐户

基本上,您的响应中应该包含以下 header 。

Access-Control-Allow-Origin: https://yourdomain.com

您还可以进行以下配置。

Access-Control-Allow-Origin: *

如果您使用withCredentials那么您不能在 Access-Control-Allow-Origin header 中使用通配符 *,您应该明确提及该域。

关于javascript - 外部 API 未处理 CORS 预检请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077982/

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