Dylan Hunt Dylan Hunt - 3 months ago 23
Node.js Question

In Node+Express, how can I set CORS for individual routes?

I am using express-cors npm package, but any way will do:

I tried this for a public route:

// @ /routes/index.js
var cors = require('express-cors');
var express = require('express');
var router = express.Router();

// Set cross-origin rules
router.use(cors({
allowedOrigins: [
'*'
]
}));

// GET home page
router.get('/', function(req, res, next) {
res.render('index', { title: 'tol-node-public' });
});

module.exports = router;


I also tried a private route to allow access from my website:

// Set cross-origin rules
router.use(cors({
allowedOrigins: [
'https://*.mysite.*'
]
}));


But upon my Ajax call:

$.ajax({
url: 'https://api.mysite.com/',
dataType: 'html',
type: 'GET',
success: function (res) {
console.log( "NODE SERVER STATUS: " + JSON.stringify(res) );
},
error: function (xhr, status, errThrown) {
if (DEBUG) console.log( "**ERR @ CheckNodeStatus: " + JSON.stringify(res) );
}
});


I am getting an err for no CORS, so access denied. How can I fix my CORS? I am still new at Node.

Answer

I have not used npm express-cors before, but I have used npm cors so I can only discuss how to use that.

To set up:

npm i -S cors


index.js:

// @ /routes/index.js
var cors = require('cors');
var app = require('express')();

// Allow all
app.use(cors());

// GET home page
app.get('/', function(req, res, next) {
  res.render('index', { title: 'tol-node-public' });
});

module.exports = router;

Or set up for your particular api, on a particular route (in this case the root route):

var corsOptions = {
  origin: 'https://api.mysite.com/',
  optionsSuccessStatus: 200
};

app.get('/', cors(corsOptions), function(req, res, next){
  res.render('index', { title: 'tol-node-public' });
});

There are many other options available using this package.

Documentation for npm cors here.

Comments