【问题标题】:CORS preflight response incorrect/empty headersCORS 预检响应不正确/空标头
【发布时间】:2017-10-08 03:32:59
【问题描述】:

我有 /api/test 的 cors 这样设置:

Allow-Origin: http://localhost:8133
Allow-Headers: X-MyHeader
Allow-Method: Get

services.AddCors(options =>
{
    options.AddPolicy("default", policy =>
    {
        policy.WithOrigins("http://localhost:8133")
            .WithHeaders("X-MyHeader")
            .WithMethods("GET");
    });
});

app.UseCors("default");

如果我使用 axios 向 /api/test 发送带有标题 X-MyHeader 的 get 请求,它会发送 OPTIONS 请求,例如

Access-Control-Request-Headers: x-myheader
Access-Control-Request-Method: GET
Host: localhost:8132
Origin: http://localhost:8133

我收到了回复

Access-Control-Allow-Headers: x-myheader
Access-Control-Allow-Origin: http://localhost:8133
Date: {whatever}
server: {whatever}

为什么缺少Access-Control-Allow-Method 标头?


现在,如果我添加另一个标题,例如 X-NotSupportedHeader,例如

Access-Control-Request-Headers: x-notsupportedheader
Access-Control-Request-Method: GET
Host: localhost:8132
Origin: http://localhost:8133

我的回答是

Date: {whatever}
server: {whatever}

在控制台中我们得到

XMLHttpRequest cannot load http://localhost:8132/api/test. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8133' is therefore not allowed access.

如果任何条件失败,为什么根本没有设置 Access-Control-Allow-* 标头?

【问题讨论】:

    标签: asp.net-core cors axios


    【解决方案1】:

    没关系,只需阅读规范即可。

    https://www.w3.org/TR/cors/#resource-preflight-requests

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 2020-02-21
      • 2013-05-17
      • 1970-01-01
      • 2021-11-12
      • 2020-09-21
      • 2016-12-19
      • 2017-04-11
      • 2017-08-01
      相关资源
      最近更新 更多