Apache2 服务器将 Access-Control-Allow-Origin header 应用于除 XHR 之外的每个响应

Apache2 server applies Access-Control-Allow-Origin header to every response EXCEPT XHR

我正在测试使用 apache httpd 部署我的 CRA 应用程序。它正在消耗外部 API,因此我需要配置 Access-Control-Allow-Origin header 以允许这样做。

我添加了一个规则,用于将 Access-Control-Allow-Origin header 添加到 .htaccess 文件。

.htaccess:

Header always set Access-Control-Allow-Origin "*"

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

javascript http 请求:

Axios.get(URL).then(successCallback).catch(errorCallback);

对我本地主机上服务器请求的响应将 Access-Control-Allow-Origin 设置为正确的值;但是,鉴于 Chrome 显示此错误,它向外部 API 发出的一个请求在响应中似乎根本没有此 header:

Access to XMLHttpRequest at '{URL}’ 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.

我检查过 headers 和重写模块在 httpd.conf 中启用。我已经阅读了所有关于启用此功能的各种指南,但没有取得任何成功。

The responses to the requests to the server on my localhost have the Access-Control-Allow-Origin set to the correct value; However, the one request it makes to an external API does not seem to have this header at all on the response

您本地主机上的服务器和外部 API 是不同的服务器

本地服务器的配置文件不会影响远程服务器。

您需要配置该服务器以使用 CORS 授予权限。