How To Fix CORS AJAX In Chrome Extension

Recently I return to work on my extension that allow people to save pages to a remote site and also highlight and comment on the page they save (sounds cool?).

When saving a particular page to my server (using fetch/jQuery post), I got this error message:

The error reads like this:

Access to fetch at 'https://openexl.com/api/fr/save-page' from origin 'https://stackoverflow.com' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

What the extension tried to do was to save a stackoverflow.com page to my server at openexl.com.

We go a CORS error.

Understanding the error

At first, I didn’t read the error message but tried to search for every possible solution online to inject into my Nginx server. After hours of searching, no solution works.

Then I came across this comment on stackoverflow:

Things start to become clear to me. As I looked closers to the preflight request initiated by Chrome, it requested two headers: authorization and content-type. However, in the response headers, the field access-control-allow-headers doesn’t contain such those two.

How to fix CORS error on Nginx

With a clear understanding of the error, the fix came pretty simple. In the server block of my website. I set this:

    location / {
        try_files $uri $uri/ /index.php?$args;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, HEAD, PUT, PATCH';

        add_header 'Access-Control-Allow-Headers' 'x-requested-with';

        if ($request_method = 'OPTIONS') {


            #...
            add_header 'Access-Control-Allow-Headers' '*';
        }
    }

Now, when Chrome send a preflight request, it knows that all request headers are allowed.

Sure enough, on the next request, I got no CORS error.

Conclusion

Obviously, you can limit the allowed headers to what you need (not setting a wildcard like I did). CORS errors don’t limit just to these headers. You may got different errors but the tip is look exact at the error message an accommodate to the browser’s requests.

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *