'preflight request CORS issue in expressJS

In my express/react app I'm trying to force an error to give user feedback on the frontend but I do not get a response.

I'm sending a request to a path that 'does not exist' but is ends up here:

router.use((res, req, next) => {
  const error = new Error('Not found')
  error.statusCode = 404;
  throw error
})

and I have an epressJS middleware error-handler:

app.use((error, req, res, next) => {
  const status = error.statusCode || 500;
  const message = error.message; 
  res.status(status).json({ message: message, data: data });
});

I'm handling CORS like this:

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Origin', 'Content-Type, Authorization');
  next();
});

Using console.log I see the request does go through my route handler and is then sent to the express error-handler as expected. However, I do not get a response in the browser. Instead, I get this error: response to preflight request doesn't pass it does not have http ok status. Sending the same request from Postman I do get the response with the error-message.

What is going wrong here?



Solution 1:[1]

I found a solution, which to my knowledge is best practice for avoiding the preflight OPTIONS request to cause CORS errors:

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

In app.js I added the if check to make sure I always send a 200 status-code to any OPTIONS requests.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AndyOh