CORS 预检响应 incorrect/empty headers

CORS preflight response incorrect/empty headers

我为 /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 使用 header X-MyHeader/api/test 发送一个获取请求,它会发送一个 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 header 不见了?


现在,如果我添加另一个 header,例如 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-* header?

没关系,请阅读规范。

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