Cross Domain AngularJS + NodeJS

Introduction

Last 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-to

First 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 :

Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
Access-Control-Allow-Credentials: "true"
Access-Control-Allow-Headers: "content-type"


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.

Conclusion

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.

Most seen