[Fixed] Access-Control-Allow-Origin value mismatch between express and axios

Issue

This question differs slightly from CORS questions wherein the answer was adding Access-Control-Allow-Origin header (such as this one). I am adding the header, however it sounds that there is a mismatch between what my server side sends in that header and how my client side sees it

I have a React application in the client side running on localhost:3000 and a node.js app running on localhost:8080. React uses axios for communicating with the back-end and node.js uses express to receive requests from the front-end

  • In the client side I have the below axios request. I am adding withCredentials options witch in turn will require Access-Control-Allow-Origin set in the server side
        axios.post('http://localhost:8080/playlist/', {playlistId: playlistId}, {withCredentials: true})
            .then(response => console.log("it worked"))
            .catch(err => console.log({...err}))
  • In the server side I enabled cors in express. Please not how my origin parameter does not contain a slash at the end:
app.use(cors({credentials: true, origin: 'http://localhost:3000' }))
  • When I make the request from the client side, I receive an exception saying that my Access-Control-Allow-Origin in the response is not equal to the Origin header in the request. Notice that the only difference seems to be the slash at the end. But as previously mentioned I set exactly ´http://localhost:3000´ (without the slash).

enter image description here

enter image description here

  • Inspecting the HTTP call through Wireshark shows that indeed there is a slash in the Origin Header that I didn’t add

enter image description here

Has anyone faced the same problem and found a solution and/or workaround?

Update:

For every request, two HTTP calls are being sent, first OPTIONS and then POST. The OPTIONS call is responded by express with the correct Access-Control-Allow-Origin

enter image description here~

Update 2:

There was a hard-coded res.set('Access-Control-Allow-Origin', 'http://localhost: 3000/') in that route that was adding the slash. That’s the reason why the OPTIONS call made by the browser adds the header without the slash, but the subsequent POST call adds the slash

Solution

Try this:

const cors = require('cors');

const whitelist = ['http://localhost:3000'];

var corsOptionsDelegate = (req, callback) => {
  var corsOptions;
  if (whitelist.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true };
  } else {
    corsOptions = { origin: false };
  }
  callback(null, corsOptions);
};

...

app.use(cors(corsOptionsDelegate))

Leave a Reply

(*) Required, Your email will not be published