我正在创建一个 express
服务器。这是片段。
const app = express();
app.use(cookieParser()); // mainly used to retrieve and store CSSO tokens
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "https://the.real.url.com:8081");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Expose-Headers", "Content-Disposition, Content-Type");
res.header("Access-Control-Allow-Credentials", true);
next();
});
目前正在运行。但我需要将 https://the.real.url.com:8081
替换为 regex
。
首先,它可以是 https
或只是 http
。
其次,可能有也可能没有端口。等等。
所以当我编辑它时 https?://the.real.url.com:8081
允许 http
和 https
。
我收到此错误
“Access-Control-Allow-Origin” header 包含无效值“https?://the.real.url.com:8081”。因此不允许访问源“https://the.real.url.com:8081”。
我还尝试了 http(s?)://the.real.url.com:8081
、https?://*
和其他变体。它们都不起作用。
所以我想知道 Regex
是不允许的吗?但是通配符 *
有效。
我做错了吗?
最佳答案
您是否查看过 express 的 cors 包:https://github.com/expressjs/cors ,这允许您对原点使用正则表达式:
var express = require('express');
var cors = require('cors');
var app = express();
var corsOptions = {
origin: /example\.com$/,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
};
app.use(cors(corsOptions));
您还可以在单个端点上使用此包,例如
app.get('/test/', cors(corsOptions), function (req, res, next) {
res.json({msg: 'Success'});
});
关于node.js - Node Express 服务器中的 CORS 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49240051/