How to allow the Access-Control-Allow-Origin header using HTML5 fetch API with JavaScript?

Spread the love

Sometimes, we want to allow the Access-Control-Allow-Origin header using HTML5 fetch API with JavaScript.

In this article, we’ll look at how to allow the Access-Control-Allow-Origin header using HTML5 fetch API with JavaScript.

How to allow the Access-Control-Allow-Origin header using HTML5 fetch API with JavaScript?

To allow the Access-Control-Allow-Origin header using HTML5 fetch API with JavaScript, we should enable CORS on server side.

For instance, we write

const allowCrossDomain = (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  next();
};
app.use(allowCrossDomain);

to call the Express app.use method to add the allowCrossDomain middleware into our app.

In it, we call res.header with the response header keys and values to enable CORS.

Leave a Reply

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