简体   繁体   English

在Node + Express中,如何为各个路由设置CORS?

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

I am using express-cors npm package, but any way will do: 我正在使用express-cors npm包,但任何方式都可以:

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电话上:

$.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. 我因为没有CORS而得到错误,因此拒绝访问。 How can I fix my CORS? 我该如何修复我的CORS? I am still new at Node. 我还是Node的新手。

I have not used npm express-cors before, but I have used npm cors so I can only discuss how to use that. 我之前没有使用过npm express-cors ,但我使用过npm cors所以我只能讨论如何使用它。

To set up: 建立:

npm i -S cors


index.js: 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): 或者在特定路径上设置特定的api(在这种情况下是根路由):

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. npm cors的文档在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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