Categories
JavaScript Answers

How to enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *