Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Enabling CORS on Node JS

DZone's Guide to

Enabling CORS on Node JS

This post shows how to enable Cross Origin Resource Sharing CORS in Node. CORS essentially means cross-domain requests. Read on and see how it's done.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

This post shows how to enable Cross Origin Resource Sharing CORS in Node. CORS essentially means cross-domain requests.

Simply using this line of code to set a header on your response will enable CORS.

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

This code snippet, however, would enable CORS for all resources on your server.

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

This can also be used for resource files as you can see here.

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

Here is the code of a complete example:

var express = require('express');

var app = express();
app.use(function(req, res, next) {
  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 = {
    "Fruits": [
      "apple",
      "orange"    ]
  };

  res.json(data);
});

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
cors ,cors enabled ,node ,node js

Published at DZone with permission of Madhuka Udantha, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}