Call Us Today!

Blog

Enable CORS on Node.js and Apache

This post is a quick recipe to enable CORS in Node and Apache. CORS means cross-domain requests and they are usually forbidden due to some kind of security reason.

It’s assumed that you are reading this because you know Node or a bit of Apache.

Test your work

Regardless of whether you’re working on Node, Apache or something else, there is a header-checking tool that comes in very handy to see if your configuration changes are actually working. By using WebConfs.com you can quickly and easily see if your server is adding the headers you want to add or not.

Node

Simply use these two lines of code in the route that you wish to make accessible to requests from other domains:


res.header("Access-Control-Allow-Origin", "*");

You can also use a middleware to enable CORS for all the routes in that server:


app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
next();
});

Apache

Enabling CORS on apache is a two-step process. First you must create a file with the name .htaccess and add it to the directory where your cross-domain-friendly files are. We recommend you create a new directory for this. The file must contain the following code, (lines 2 and 3 may be optional):


Header always set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

The second step in the process is to enable .htaccess files. Test out the CORS requests and see if they are already working (some installations of Apache come with .htaccess files already enabled). In order to test if it’s working, reload apache (using the command below) and then fire your ajax request at your server.


sudo service apache2 restart

If that worked, you’re done. If not, then you need to add the following code inside the VirtualHosts section of your 000-default.conf in your /etc/apache2/sites-available folder:


<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

Make sure you replace the /var/www/ with the actual path to your document root. Congrats! You’re done!

No Waiting list! Start your journey today!

FVI School of Nursing and Technology has NO waiting list and three start dates a year so you can begin nursing school when you're ready

Schedule a Career Planning Session