Skip to content

Instantly share code, notes, and snippets.

@RayanBassetti
Created January 26, 2020 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RayanBassetti/530df882452b0b3e174bb00749d4ee39 to your computer and use it in GitHub Desktop.
Save RayanBassetti/530df882452b0b3e174bb00749d4ee39 to your computer and use it in GitHub Desktop.
Middleware to prevent cors errors (Express.js)
// middleware that ensures that cors errors are prevented
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // allow the access of the api, to all clients/websites asking
res.header('Access-Control-Allow-Headers', '*'); // which kind of header we want to accept
if(req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE');
return res.status(200).json({});
}
next();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment