1
votes

https://example.com fire ajax pre-request(beforeSend) to 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 console return error message

XMLHttpRequest cannot load https://api.example.com/auth. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

2

2 Answers

3
votes
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
votes

I added this to Nginx and it worked:

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

For the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:3000' is therefore not allowed access.

I added this to Nginx:

add_header Access-Control-Allow-Origin *;