Enable CORS

Learn how to enable cross-origin resource sharing.

We can use third-party middleware to add functionality to Express applications, including support for cross-origin resource sharing (CORS).

Cross-Origin Resource Sharing (CORS)

By default, any requests that come from an origin other than the server hosting our application, such as mysite.com and facebook.com, will be blocked.

So, if a website that’s hosted on a different origin tries to make GET requests to the Express server, the requests would be blocked unless the website is added to a CORS whitelist in Express.

The npm package cors is a middleware that allows us to configure CORS in Express applications with various options. By default, the cors package just enables resource sharing and access for all origins.

  1. Install cors by running the following command in the project folder in the terminal below:

Get hands-on with 1400+ tech skills courses.