Enable CORS in a Node.js Application

The Problem

So… you are creating an awesome Single Page Application with your favorite front-end framework (Vue.js, Angular, etc…) you need to connect your app with an external service; you have selected a JavaScript library to make the AJAX calls (like Axios), everything seem to be perfect, you create your method to get the remote data with something like this:

var serverURL = 'http://example.com:3000/my-rest-api-end-point-to-get-data';
var _this = this;
var configAxios = {
    url: serverURL,
    method: 'get',
    responseType: 'json',
    data: {},
    headers: {}
};

// Getting information using Axios library
axios.request(configAxios).then(function(response) {
    console.log(response);
    _this.myData = response.data;
});

And suddenly, your app is broken, why? If you go to the console, you will see an error similar to this one:

No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. The response had HTTP status code 401.

The Solution

Because of security, you cannot request resources that are not in your domain (same server, same port). The solution is quite simple:

You need to authorize the origins that can make this type of calls.

This authorization is known as enabling CORS, this operation needs to be done in your SERVER. Here is an example using an Express.js application, see step 3 in the comments:

const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);

const morgan = require('morgan');
const bodyParser = require('body-parser');

const port = process.env.PORT || 3300;

const pollsRouter = require('./api/routers/polls-router');
const pollsService = require('./api/services/polls-dummy.service');

// 1. Morgan middleware for logging
app.use(morgan('dev'));

// 2. Express static index.html file
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// 3. Enable CORS on ExpressJS to avoid cross-origin errors when calling this server using AJAX
// We are authorizing all domains to be able to manage information via AJAX (this is just for development)

app.use(function(req, res, next) {
    // Instead of "*" you should enable only specific origins
    res.header('Access-Control-Allow-Origin', '*');
    // Supported HTTP verbs
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    // Other custom headers
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

// 4. Body parser middleware to auto-parse request body to JSON
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


// 5. Run the server
server.listen(port, () => {
    console.log('Server active on port: %d', port);
});

Simple and fast, I hope you find this useful for your implementations.

See you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *