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

12,361

Solution 1

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

Solution 2

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 *;
Share:
12,361
Samuel Lui
Author by

Samuel Lui

Updated on November 21, 2022

Comments

  • Samuel Lui
    Samuel Lui over 1 year

    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.

  • Jaromanda X
    Jaromanda X almost 7 years
    Is this a solution? Just wondering because there's no explanation of what this is or where this code belongs
  • Libby Lebyane
    Libby Lebyane about 4 years
    the solution posted above works for me, this needs to be added in /etc/nginx/sites-available/default in the suspicious server.