How to enable CORS in Express.js

/ By Arjun / Published on February 22, 2018

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.
Chrome:

Firefox:

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Chris Jones
1 month ago

Thanks Arjun. I kept getting partial or non-working answer about CORS on other sites, but your explanation and sample worked great.

1
0
Would love your thoughts, please comment.x
()
x