在Express JS中允许多个CORS域 [英] Allow multiple CORS domain in express js
本文介绍了在Express JS中允许多个CORS域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以简化的方式允许多个域用于CORS。
How do I allow multiple domains for CORS in express in a simplified way.
我有
cors: {
origin: "www.one.com";
}
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
此功能仅在来源$ c中提到一个域名时有效$ c>
但是如果我想将来源
作为一个域数组,并且我想允许CORS用于原始数组中的所有域,我都会有这样的内容-
But if I want to have origin
as an array of domains and I want to allow CORS for all the domains in the origin array, I would have something like this -
cors: {
origin: ["www.one.com","www.two.com","www.three.com"];
}
但是接下来的问题是,下面的代码不起作用-
But then the problem is this below code would not work -
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
我如何获取 res.header
通过 cors.origin
吗?
推荐答案
cors模块: https://www.npmjs.org/package/cors
它为您完成了此类工作-检查 配置CORS w /动态起源-部分
I would recommend the cors-module: https://www.npmjs.org/package/cors It does this kind of stuff for you - check the "Configuring CORS w/ Dynamic Origin"-Section
这篇关于在Express JS中允许多个CORS域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文