Node.js – How to enable Cross Origin Resource Sharing (CORS)

Enabling CORS on a Node.js server can be done using the code snippet below.
This code uses express as the framework for node development.

var express = require('express');

var app = express();

app.use(function(req, res, next) {
  // add the access control headers
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function (req, res) {
  var data = {};
  res.json(data);
});

app.get('/download', function(req, res){
  var file = __dirname + '/download.tar';
  res.download(file); // Set disposition and send it.
});

Hope this is helpful!

Add a Comment

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image