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

时间:2017-05-21 03:58:47

标签: javascript ajax nginx jwt preflight

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不允许授权。

2 个答案:

答案 0 :(得分:0)

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;
    }
}

答案 1 :(得分:0)

我将其添加到Nginx并有效:

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

对于错误:

  

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

我将此添加到了Nginx:

add_header Access-Control-Allow-Origin *;