Home > Blockchain >  Cannot fetch from localhost with Authorization header
Cannot fetch from localhost with Authorization header

Time:09-17

I'm having a hard time sending a get request to my expressjs backend with the fetch method.

fetch('http://localhost:9000', { method: 'GET', headers: { Authorization: `Bearer ${accessToken.accessToken}` }}).then(() => {
    debugger
}).catch((error) => {
    debugger
})

Based on what I could read, this seems correct - The request is however not reaching the API.

I tried constructing the options object like so, without any luck:

const options = {
    method: "GET",
    headers: headers
};

Without the headers, my request reaches the API. Anyway, the error that I'm getting is this:

error: TypeError: Failed to fetch

CodePudding user response:

If you make that request from an origin other than http://localhost:9000, the Authorization header will cause the browser to make a CORS preflight request OPTIONS http://localhost:9000 before the GET request, and if that fails, the GET request would not be made.

You must ensure that your server handles the preflight, e.g., through the cors middleware.

CodePudding user response:

So I found a solution, basically I added this middleware in my Express application to allow CORS,

app.use((req, res, next) => {

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods", "*");

    next();
});
  • Related