by Sai gowtham

How to allow CORS origins in Express

In this tutorial, we will learn what is cors and how to handle the cors (cross-origin resource sharing) requests in Express.

What is CORS?

Cross-origin resource sharing is a mechanism that prevents you from accessing website resources from a different domain or subdomain.

For example, you are sending a http request from the https://machine-23.com to https://car-23.com/parts.json you will get a cors error because both origins are different.

Allowing cors for all origins

To allow the cors for all origins (it means you can make HTTP requests from any origins), you need to use the cors middleware package in express.

Open your terminal and install the cors package by running the following command.

npm install cors

Usage:

const express = require("express");
const cors = require("cors");
const app = express();

app.use(cors());

app.get("/hello", (req, res) => {
  res.send('hello')
});

app.listen(3000, () => console.log(`App is running`));

Allowing cors for a single route

To allow the cors for a single route instead of all routes in your express app, you need to add cors() function to that route handler function.

Example:

const express = require("express");
const cors = require("cors");
const app = express();

app.get("/hello", cors(), (req, res) => {
  res.send('hello')
});

app.listen(3000, () => console.log(`App is running`));

Allowing Multiple origins

If you want to allow multiple origins (or domains) to access your backend API instead of all origins, you need to pass an options object to the cors() function.

Example:

const express = require("express");
const cors = require("cors");
const app = express();

const allowedOrigins = ['http://open-24.com', 'http://close-24.com']const corsOptions = {
  origin: function (origin, callback) {
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions));
app.get("/hello", (req, res) => {
  res.send('hello')
});

app.listen(3000, () => console.log(`App is running`));

Now, we can only access website data from the two origins that we added to the allowedOrigins array and all other origins are blocked.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course