How to enable CORS in Express.js

In this post, you will learn about Cross-Origin Resource Sharing. Http requests are restricted by the same-origin policy, which means where scripts can be loaded from the same Origin. Specifically, the protocol, domain, and port must match. It means you can’t send the request to other origins, this restriction is there for a security reason, it will prevent the attacks.

When you send a Cross-Origin request you will get errors similar to the below shown.


How to implement CORS

CORS is implemented through the Access-Control-Allow-Origin header. The easiest way to implement it in an Express application is to use the cors package (npm install –save cors).

To enable CORS for your application:

That’s it. CORS is now enabled.

If you make a request to your app, you will notice a new header being returned:

The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).

Limit CORS to specific routes

For example to restrict CORS to paths starting with /api

Restricting allowed hosts

If you want to restrict AJAX access to a single origin, you can use the origin option:

If you would rather have a list of allowed origins, you can use a function instead of a string as the origin value:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status