How to fix “blocked by CORS policy” in express js.

Well if you are learning express js and trying to fetch your endpoints. Its highly possible that you must have seen this error or similar to this.

The request has been blocked by CORS

So, all you need to do is just make sure that your express api has a middleware configured to handle CORS issues. BTW CORS stands for “Cross Origin Resource Sharing”. This error occurs when you try to access a server (In our case the express js api) which is not configured to share its resources with you. In simpler words you are not permitted to call that paticular API.

So, In order to make your frontend (In my case its a React Js Application) or some kind of App whitelisted in the server’s configuration you need to install a simple npm package(Used by almost every web developer) “cors” via

npm i cors — save

and add a middleware at the top of your routes in the main server file. The middleware looks like this,

app.use(

If you want your api to be accessible from anywhere just put a star(*) in the quotes at the origin value and that will let your API to share data with any host.

You can configure a lot more in the cors for example you can restrict the allowed methods for routes and much more. I recommend you checking out the docs for more clear insights on this libraray and this mechanism.

https://www.npmjs.com/package/cors