⚠️ This lesson is retired and might contain outdated information.

Allow CORS in Node.js and Express

Joel Lord
InstructorJoel Lord
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 2 years ago

In this quick lesson, we see how to add the CORS middleware so that our Express server can handle requests from different origins.

Instructor: [00:00] If you have an API that runs on a different server or even a different port than your application, and you try to do a fetch, you should see a message in your console complaining about Access-Control-Allow-Origin.

[00:19] The fix for this in your Express server is very simple. First of all, you need to require the CORS library. You'll also need to install it using npm install cors. Secondly, you need to tell your Express server to use this middleware by using app.use and the library that we've just installed.

[00:46] Now, if you restart your server and try the same fetch call in your browser, you won't have that CORS error any more.

Philip Cox
Philip Cox
~ 6 years ago

Your JWT implementation completely changed from the last lesson.

Tomi
Tomi
~ 6 years ago

I agree with the above, it'd be better if each lesson built on the implementation from the previous lesson. Two downsides to the way you're doing it; a) the time it takes to go pull each lesson is time I could spend watching the lesson, and b) forces me to speculate what all this new code does?

Yes, I could quickly google e.g. what express-jwt is and I could even guess prior to but why not just use it in the previous lesson to begin with? Just makes things confusing and inconsistent.

tangorri@live.fr
tangorri@live.fr
~ 5 years ago

To enable CORS middleware that's not app.use(bodyParser.json()); but app.use(cors());

Eleonora Lester
Eleonora Lester
~ 5 years ago

Should we always user cors()? Or should we allow specific origins? Is there a good practice for production cases?

Markdown supported.
Become a member to join the discussionEnroll Today