To enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js, we add some response headers.
For instance, we write
app.all("/", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get("/", (req, res, next) => {
// Handle the get for this route
});
app.post("/", (req, res, next) => {
// Handle the post for this route
});
to call res.header
to add the Access-Control-Allow-Origin
and Access-Control-Allow-Header
response headers to enable CORS.
Then we routes to handle get and post requests from the / URL.