[Fixed] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS preflight response did not succeed)

Issue

SERVERSIDE

// Set Headers
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, authorization, Verification");
        next();
    });

app.use('/user', authMiddleware.authenticateToken, userRoutes);

CLIENTSIDE

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

I have no idea why this happens. If i remove the authMiddleware, then everything works fine.

ANSWER:
I think the problem is that I used USE instead of a specific route. When I add the middleware to a route it works fine. I thought I can use USE to add middleware but that doesn’t work.

Solution

When browsers come across a cross-origin AJAX call, it has to determine if the endpoint understands CORS protocol and what are the acceptable domains/methods/headers are. To do so they will fire Preflight Request in OPTIONS method. https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

However not all AJAX call will trigger such preflight request. For example, if you just directly call

fetch('https://google.com/some_api')

which is essentially to fire a GET call without parameters to https://google.com/some_api, browser might choose to skip preflight and just fire the actual GET call.

Leave a Reply

(*) Required, Your email will not be published