繁体   English   中英

预检响应中的 Access-Control-Allow-Headers 不允许请求头字段授权。 (nginx)

[英]Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response. (nginx)

https://example.com 将ajax pre-request(beforeSend) 发送到https://api.example.com (nginx)

$.ajax({
    method: "POST",
    url: 'https://api.example.com',
    xhrFields: {withCredentials: true},
    data: {...},
    success: function(msg) {...},
    beforeSend: function(request){
        var token = 'xxxxxx';
        request.setRequestHeader('Authorization', 'Bearer ' + token);
    },
    complete: function(msg) {},
    error: function(xhr, ajaxOptions, thrownError) {}
});

Chrome 控制台返回错误消息

XMLHttpRequest 无法加载https://api.example.com/auth 预检响应中的 Access-Control-Allow-Headers 不允许请求头字段授权。

location / {
    if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "https://example.com";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Authorization";
        add_header Access-Control-Allow-Credentials "true";
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
    }
}

我将此添加到 Nginx 并且它起作用了:

add_header Access-Control-Allow-Headers "Authorization";

对于错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此,不允许访问 Origin ' https://localhost:3000 '。

我将此添加到 Nginx:

add_header Access-Control-Allow-Origin *;

暂无
暂无

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

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