Last active
January 24, 2023 03:22
-
-
Save nicojones/872f9537567b7011c4725dd43508c478 to your computer and use it in GitHub Desktop.
When app.use(cors()) is not working for you, try this snippet. Allows CORS for your application with Express.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// imports.... | |
const app = express(); // create express app | |
// Set all headers that you need | |
const fixCors = (req, res, next) => { | |
res.setHeader("Content-Type", "application/json,text/plain"); // Add content type if needed | |
res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,UPDATE,OPTIONS"); // All methods | |
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); // Change origin if needed | |
res.setHeader("Access-Control-Allow-Headers", "Origin, Access-Control-Allow-Origin, Content-Type, Accept, Authorization, Origin, Accept, X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers"); | |
res.setHeader("Access-Control-Expose-Headers", "Origin, Access-Control-Allow-Origin, Content-Type, Accept, Authorization, Origin, Accept, X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers"); | |
res.setHeader("Access-Control-Allow-Credentials", "true"); | |
}; | |
// Make sure this is the first `app.use`. Every request will go through this. | |
app.use((req, res, next) => { fixCors(req, res, next); next(); }); | |
// For requests with OPTIONS, will approve the preflight. | |
app.options("*", (req, res, next) => { fixCors(req, res, next); console.log("send 200"); res.sendStatus(200); }); | |
// Rest of your code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment