IntroductionLast time I was working on a search engine web based application using AngularJS and NodeJS. I wanted to add some data using a Node webservice running on port 8080 of my virtual machine. So I made my post request as usual using $http module but soon I discovered that changing the server port was causing a Cross Domain request. So in this article I'll describe how I resolved the problem so my server accepts the request.
How-toFirst of all you need to know that when setting specific headers in a Cross Domain Request, the browser will make an OPTIONS request first to check if he can actually make the POST request.
Knowing that we first need to accept the request on server side by returning Allow Origin specific headers :
By answering with these headers, you say that you accepted the Cross Domain request. You can also specify a specific server origin if you need to limit the API accessibility.
As said before, this is not enough, because the browser generates an OPTIONS request, your controller will be called twice on ExpressJS side. This is why you should add a middleware to catch the OPTIONS request and return a 204 no content response.
After that, you'll have a fully compliant Cross Domain Request system in your ExpressJS.
As you know, you're rarely the first to face the problem, this is why I prefer not to recreate the wheel and reuse good pieces of software. In this case, you can use the cors npm, allowing you to easily integrate the Cross Domain Request. You can find it at https://github.com/expressjs/cors and it is easy as abc to use.
Hope it helps, and have fun.
How to make your DHT Crawler in 3 steps Why ? You all know that torrents indexers and trackers are the target of a witch hunting by ...
The problem I was making some improvements to the PlanIT project that I'm redesigning all the source code to work with AngularJS ...
NodeJS edged with C# Hi everyone, it's been a while I didn't post on my blog mainly because I didn't had the time for mainly...
Hi everybody, I'm having a big change in my life these days this is why I wasn't this available to write Blog Posts but this ...
FlyersWeb/react-presentation By FlyersWeb Slides from a React Presentation I made for other developers September 6, 2017 at 12:48AM via ...
Send e-mails with Node.JS - easy as cake! https://github.com/andris9/Nodemailer