DEV Community

LePhuongTrung
LePhuongTrung

Posted on

Fix CORS policy error on Nodejs with 2 super simple steps

What is CORS?

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

How does CORS policy error show?

Access to XMLHttpRequest at 'http://localhost:3333/user/Login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How to fix CORS policy error on nodejs?

  • Step 1: Install CORS
npm i cors
  • Step 2: put CORS in request Open the app.js file and add the following 3 lines.
var cors = require('cors')
var app = express()
app.use(cors())

Also, you can add some more customizations here: https://www.npmjs.com/package/cors

Conclusion

If you do not understand something, you can message me or join this group Zalo: Link, to exchange knowledge about BackEnd Nodejs

Top comments (0)