req.headers.origin始终未定义,如何为ALLOW-FROM允许多个域

时间:2018-08-03 10:25:59

标签: node.js express

我想允许Access-Control-Allow-Origin(CORS)和ALLOW-FROM(iframe)用于多个地址。我环顾四周,发现了这一点:

Enable Access-Control-Allow-Origin for multiple domains in nodejs

和其他一些说要做这样的事情:

const allowedOrigins = ["https://example1.com", "https://example2.com"];

if (allowedOrigins.includes(req.headers.origin)) {
    res.set("Access-Control-Allow-Origin", req.headers.origin);
    res.set("X-Frame-Options", `ALLOW-FROM ${req.headers.origin}`);
}

问题在于,req.headers.origin在开发和生产服务器中始终未定义。当我在Web检查器的“网络”选项卡中查找时,永远不会有名为 origin 的请求标头,只有 host 或有时是 referer

所以我尝试了以下操作:

const origin = `${req.protocol}://${req.headers.host}`;
res.set("Access-Control-Allow-Origin", origin);

这很好,但不能用于X-Frame-Options标头,因为 host 是网络所在的地址,而不是iframe父级的地址。我需要ALLOW-FROM https://example1.com,而不是ALLOW-FROM https://myapp.com。你能帮我吗?

1 个答案:

答案 0 :(得分:0)

我希望这是您想要的:

Configuring CORS w/ Dynamic Origin
var express = require('express')
var cors = require('cors')
var app = express()

var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})