繁体   English   中英

为什么 Axios 似乎没有收到 Access-Control-Request-* 标头,即使它们正在发送?

[英]Why does Axios not seem to receive the Access-Control-Request-* headers even though they are being sent?

背景

我目前正在构建一个 web 服务,使用无服务器和 AWS 作为后端,Axios 用于从 ReactJS 前端调用后端资源。 由于后端和前端组件发布在不同的域下,我需要使用跨域资源共享 (CORS) 来规避目前大多数浏览器强制执行的同源策略。

问题

不幸的是,即使我已经在后端配置了所有的访问控制标头(在 AWS Api 网关中),我仍然收到错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/internal/role. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

数据

现在,我遇到的问题是,当使用 Postman 在我的一个资源上调用 OPTIONS 调用(不是作为预检,而是作为“独立”调用)时,我收到了正确的访问控制标头。 但是,当使用 Axios 发出相同的请求时,我似乎没有收到这些标头,这让我认为这可能是 Axios 的问题。

这些是我在调用 OPTIONS 时收到的 Postman 标头:

 - Date: Fri, 26 Jun 2020 12:01:18 GMT
 - Content-Type: application/json
 - Content-Length: 0
 - Connection: keep-alive
 - x-amzn-RequestId: <some ID>
 - Access-Control-Allow-Origin: https://example-gui.com
 - Access-Control-Allow-Headers: Origin,Accept,Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with
 - x-amz-apigw-id: <some ID>
 - Cache-Control: max-age=600, s-maxage=600, proxy-revalidate
 - Access-Control-Allow-Methods: OPTIONS,POST
 - Access-Control-Allow-Credentials: true

这些是头文件 Axios 告诉我它在进行 OPTIONS 调用时收到:

 - cache-control: max-age=600, s-maxage=600, proxy-revalidate
 - content-length: 0
 - content-type: application/json

但是,当使用 Firefox 的开发工具时,我可以看到实际上返回了所有标题,如 Postman 列表中所示。 我不知道 Axios 是只是隐藏了这些字段还是出于某种原因不处理它们。

不幸的是,我没有关于实际 POST 调用返回的数据的信息,因为它只是抛出了提到的异常。

编码

The Postman call is just a basic call to the respective URL with the OPTIONS method that only has one additional header (Authorization) so I'm not going to go into that any further.

Axios 调用源自 URL https://example-gui.com/#/调用如下:

const fullResponse = (response: AxiosResponse) => response;

const backendRequests = {
   ...
  options: (url: string, header: {}) =>
    axios.options(url, header).then(fullResponse),
  ...
};

const loginRequests = {
  getUserRole: (accesstoken: string) =>
    backendRequests.options(
      "https://example.com/internal/role",
      { Authorization: `Bearer ${accesstoken}` }
    ),
};

然后我打印这样的结果:

try {
  await agent.loginRequests
    .getUserRole(this.accessToken)
    .then((response) => {
      console.log(response); // <-- Printing the results
      <...>
    });
} catch (error) {
  console.log(error);
}

这是我从“数据”部分中获得列表的地方。

问题

这是否可能是 Axios 框架中的一个错误,它是一个基于配置的问题,其中 Axios 调用必须事先以不同的方式设置才能接收所有标头,还是问题出在其他地方?

考虑到所有这些信息,我如何才能设法通过同源策略?

您是否检查过是否从 Axios Access-Control-Allow-Headers header 下发送后端服务请求的所有标头。 也许将标题数量限制为Access-Control-Allow-Headers: Accept,Content-Type并检查 CORS 是否正常工作。

如果 Access-Control-Allow-Origin 使用 *. 您必须指定协议 + 域 + 端口。

Access-Control-Allow-Origin 通配符子域、端口和协议 使用凭证进行跨域资源共享 使用 * 过于开放,会破坏凭证的使用。 因此,将 http://domain:port 设置为允许来源 header 进一步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM