Simple Steps to Fix CORS Error While Connecting a Front-End App to a Node.js/Express.js App

Hemant Jain
The Startup
Published in
4 min readDec 29, 2020

--

Typical CORS error
Typical CORS Error

Ever came across this error?

Access to XMLHttpRequest at ‘http://localhost:8000/users/' from origin ‘http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘http://localhost:3000/' that is not equal to the supplied origin.

If yes, here are simple steps that you need to follow in order to address this issue. First things first, if you wanna know about CORS policy and its advantages, please refer to this link. In short, CORS helps in making the application more secure.

Note: I presume that your Node.js app is already built and I will only be providing some steps to fix the error.

Step 1:

Open your Node.js application in your favorite IDE and go to the root directory. Open the terminal and type:

npm install cors

and press enter. Cors will be installed on your app.

Step 2:

Now let’s configure the cors module. In your Node.js app, go to the folder containing the file in which all the routes are defined. In the same folder(not necessarily, but only for convenience), create a new file and name it ‘cors.js’. Now add the following code to cors.js:

//cors.jsconst express = require(‘express’);
const cors = require(‘cors’);
const app = express();
const allowedOrigins= [‘http://localhost:3000', ‘http://(your computer’s name):3000’];var corsOptionsDelegate = (req, callback) => {
var corsOptions;
console.log(req.header(‘Origin’));
if(allowedOrigins.indexOf(req.header(‘Origin’)) !== -1) {
corsOptions = { origin: true };
}
else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);

In the snippet given above, you may notice a constant named ‘allowedOrigins’ which contains all the URLs which may access the back-end app. In our case, we need to mention the URL where our front-end app is hosted, which is usually localhost during development. Make sure that you mention correct port (3000 in the example). Also, don’t forget to add the second URL in which you need to mention your computer’s name.

Don’t know what your computer’s name is? Not a problem, just open the command prompt and type “hostname” and press enter. The name of your computer will be displayed.

Step 3:

Now we need to configure the routes. Let us say we want to access the sign up API from front-end app. Firstly, we will update our app.js(or index.js whichever is the starting point of your app). Please add following lines of code to your app.js

//app.js
const app = express();
var path = require(‘path’);

// view engine setup (add if not already present)
app.set(‘views’, path.join(__dirname, ‘views’));
app.set(‘view engine’, ‘jade’);

//require the file containing the ‘sign up’ endpoint
const authRoutes = require(‘./routes/authRoutes’);
app.use('/auth', authRoutes);

Similary modify the authRoutes.js file as shown below:

//authRoutes.js//signUpValidator checks if the body contains related fields or not, //you will need to write the code for it. You may skip it in case //you want to.const signUpValidator = require(‘../validators/signUpValidator’);//signUpController forwards the request to business logic layer, you //may implement the business logic directly and skip the //signUpControllerconst signUpController = require(‘../controllers/signUpController’);
const cors = require(‘./cors’);
const express = require(‘express’);
const authRouter = express.Router();
authRouter.route(‘/users/signup’)
.options(cors.corsWithOptions, (req, res) => {res.sendStatus(200);})
.get(cors.corsWithOptions, (req, res, next) => {
res.statusCode = 403;
res.end(‘GET operation not supported on /signup’);
})
.post(cors.corsWithOptions, signUpValidator.validate, signUpController.signUp)
.put(cors.corsWithOptions, (req, res, next) => {
res.sendStatus = 403;
res.end(‘PUT operation not supported on /signup’);
})
.delete(cors.corsWithOptions, (req, res, next) => {
res.sendStatus = 403;
res.end(‘delete operation not supported on /signup’);
});

What have we done here? Firstly, we have required the cors.js file which we had created earlier. Then we have defined the sign-up endpoint beginning with options() which simply takes care of CORS preflight. I have used POST method to sign-up but many developers prefer using PUT, and it is your call which you wanna go with. The corsWithOptions function makes sure that the request is originated from one of the sources which are listed in allowedOrigins (in cors.js). Similarly, you may modify all the route endpoints by adding CORS policy just as we did for sign-up. Three major points to keep in mind are:

  • Require cors from cors.js
  • Use options at the beginning of each end-point
  • For each type of request, you need to use corsWithOptions. You may also use cors.cors() in place of cors.corsWithOptions() if you wanna allow the requests originating from all origins.

The back-end app is now ready to serve the client app. The sign-up endpoint can be accessed at ‘http://localhost:{port}/auth/users/signup’.

Additional Resources:

You might wanna refer to a few links in case you like going deep into the topic.

--

--

Hemant Jain
The Startup
0 Followers

Software dev who enjoys photography