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

dyl*_*724 12 javascript node.js express

我正在使用express-cors npm 包,但任何方式都可以:

我在公共路线上尝试过这个:

// @ /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;
Run Code Online (Sandbox Code Playgroud)

我还尝试了私人路线以允许从我的网站访问:

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

但是在我的 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) );
    }
});
Run Code Online (Sandbox Code Playgroud)

我收到了 no CORS 错误,因此访问被拒绝。如何修复我的 CORS?我还是 Node 的新手。

ale*_*xi2 5

我以前没用过npm express-cors,但我用过,npm cors所以只能讨论如何使用。

建立:

npm i -S cors


索引.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;
Run Code Online (Sandbox Code Playgroud)

或者在特定路由(在本例中为根路由)上为您的特定 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' });
});
Run Code Online (Sandbox Code Playgroud)

使用此包还有许多其他选项。

npm cors 的文档在这里。

  • 我正在使用 `var router = express.Router();` - 我可以使用 router.use() 而不是 app.use 对于这个特定的路由器吗?现在尝试你的代码 (5认同)