node.js - 如何在 cors Dynamic Origin 中获取 IP 地址?
问题描述
我用nodejs构建restAPI,我想限制用户访问白名单的ip或域,为此我使用NPM的CORS包,但我无法获取访问restAPI的客户端IP地址,所以..如何获取IP地址?
这里的代码:
const whitelist = ['http://localhost', 'http://127.0.0.1']
const corsOptions = {
origin: function (origin, callback) {
console.log(whitelist.indexOf(origin))
console.log(origin)
// if (whitelist.indexOf(origin) !== -1) {
if (whitelist.indexOf('127.0.0.1') !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Your ip address is not whitelisted'))
}
},
methods: ["GET", "PUT", "POST", "DELETE", "HEAD", "PATCH"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true
}
app.get('/v2/cors', Cors(corsOptions), (req, res) => {
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' })
})
解决方案
我假设您希望基于用户的 IP 地址而不是基于域名(即来源)提供访问权限。在包的文档中,他们提到为此使用 corsOptionsDelegate。尝试这个...
const whitelist = ['http://localhost', 'http://127.0.0.1']
var corsOptionsDelegate = function (req, callback) {
const corsOptions = {
methods: ["GET", "PUT", "POST", "DELETE", "HEAD", "PATCH"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true
};
const myIpAddress = req.connection.remoteAddress; // This is where you get the IP address from the request
if (whitelist.indexOf(myIpAddress) !== -1) {
corsOptions.origin = true
} else {
corsOptions.origin = false
}
callback(null, corsOptions);
}
app.get('/v2/cors', Cors(corsOptionsDelegate), (req, res) => {
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' })
})
推荐阅读
- android - 是否有通过拖放重新排序后获取 RecyclerView 新元素顺序的功能?
- vue.js - 为什么我的 vue-svg-loader 配置无法识别 SVG 文件?
- python - 如何在 Python 中拆分记录?
- android - 如何从主要活动中停止广播接收器?
- java - 无法将变量初始化为 ArrayList.clone()
- angular - Angular 组件定义中的 Providers、ChangeDetection、Encapsulations、host
- emacs - Racket-Mode:我可以在 REPL 的给定命名空间内评估单个表单吗?
- python-3.x - 替换所有“?” 在所有列中都带有“NaN”
- javascript - 修改字符串的索引
- python - 创建一个新列以查找日期范围