3

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 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is this a solution? Just wondering because there's no explanation of what this is or where this code belongs
the solution posted above works for me, this needs to be added in /etc/nginx/sites-available/default in the suspicious server.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.