简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM