A Javascript application can only access the same origin HTTP request from the browsers. If you are developing a web application which does ajax requests to another server then you may be getting an error like No Access-Control-Allow-Origin header is present on the requested resource.

What does the above line mean? It is simply saying that your web server is not sending back the headers that allow Cross-Origin Resource Sharing ( CORS ).

In this article, I will show you how to enable CORS to a Node.js Express.js Framework.

What Is Cross-Origin Resource Sharing

Cross-Origin Resource Sharing is a mechanism that uses additional HTTP headers to tell the browser to let a web application running at one origin have permission to access selected resources from a server at a different origin.

Example

Suppose, there are two domains A and B. Now A wants to send requests to B, so by default, A can not do that if B has been explicitly allowed that request from A, or allow from anyone because of the CORS rules.

Why Is Cross-Origin Resource Sharing (CORS) Necessary

When you are building a Single Page Application(SPA) using Angular, React, Vue.js or any other frontend framework, then there are most of the cases when your backend is on another domain and you have to make a request to that domain to access the resources. You can only do this if you have properly configured CORS in your domain.

Apart from this, there are lots of other use cases of using the CORS in the application development.

Some of them are listed below:

Know About the CORS Response

Access-Control-Allow-Origin HTTP header specifies which origins can access the resources. This is one of the most used HTTPS CORS headers.

Know About CORS Request Type

There are two types of CORS request presents a simple request and a preflight request.

A simple request is that request which meets the below certain criteria :

GET / POST / HEAD method is used

/ / method is used Only application/x-www-form-urlencoded , multipart/form-data , or text/plain allows in Content-Type header.

, , or allows in Content-Type header. No event listener is used in XMLHttpRequestUpload

All the requests which don’t meet the above criteria, known as preflight requests. In the preflight requests, OPTIONS header is used. It is sent before the original request. It checks whether or not the original request is safe to proceed further.

How to Enable CORS to a Node.js Express App

Now before going further with this article, I will recommend you yo read how to create an HTTP server in Node.js and how to use express.js framework in the node.js web development.

Due to the express.js middlewares, it is very easy to enable CORS in a node.js express app.

For this article, we are going to use a simple node.js express app which just handles simple requests.

Below is the simple code which enables CORS in node.js express app.

import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors()); /* your regular routes go here */

That’s it, just 4 lines of the code and CORS is enabled in your node.js express app. Now if you make a request, you will get a new header

Access-Control-Allow-Origin: *

There are lots of other things you can do using the CORS middleware.

Restrict the Allowed Host

By default, your API resources can be accessed by any of the domain present in the world which increases the security issue.

You can restrict the domain who can access API resources.

For a single domain, you just need to modify the code like below

import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors({ origin: 'http://alloweddomain.com' })); /* your regular routes go here */

But If you have more than one domain who can access the resources of the API then you can do that by using the below code

import express from 'express'; import cors from 'cors'; const app = express(); const whitleListDomain = ['http://localhost:3000', 'http://alloweddomain.com']; app.use(cors({ origin: function(origin, callback){ // allow requests with no origin // (like mobile apps or curl requests) if(!origin) return callback(null, true); if(whitleListDomain.indexOf(origin) === -1){ var msg = 'The CORS policy for this site does not ' + 'allow access from the specified Origin.'; return callback(new Error(msg), false); } return callback(null, true); } }));

Conclusion

After reading this article, you can now enable CORS in node.js express app easily. If you can learn more about the CORS, OPTIONS and preflight then I would recommend you to read the MDN Docs on CORS.

You can join our Facebook group where like-minded people will try to solve your queries.