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

Sam*_*Lui 2 javascript ajax nginx jwt preflight

https://example.com触发 ajax 预请求(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) {}
});
Run Code Online (Sandbox Code Playgroud)

Chrome 控制台返回错误消息

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

Sam*_*Lui 5

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个解决方案吗?只是想知道,因为没有解释这是什么或该代码所属的位置 (7认同)