Firebase 函数:如何从客户端获取 IP 地址?
Firebase Functions : How to get IP address from client?
我正在尝试使用 javascript 在 firebase 函数中从客户端获取 IP 地址。为什么我需要IP?制作可以访问我的功能的白名单IP。
我的目标:通过 IP 地址访问我的功能
我尝试使用此方法但对我不起作用它给了我 'undefined' :
exports.getIP = functions.https.onRequest(async (req, res) => {
var call = req.ip
console.log(call);
res.send(call);
});
exports.getIP = functions.https.onRequest(async (req, res) => {
var call = req.headers['x-forwarded-for']
console.log(call);
res.send(call);
});
这里当我调用 req.headers :
'x-forwarded-for'
和 x-appengine-user-ip
header 都将在您部署云函数时添加。您似乎正在使用在本地主机上运行的 Firebase Functions 模拟器(因为 host header 是 localhost:5001
)。您可以尝试部署该功能并记录 IP。
The X-Forwarded-For
(XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer.
The X-Appengine-User-IP
is set by App Engine.
当您在本地模拟函数时,两者之间没有代理,因此缺少 header。
参考文献:
我正在尝试使用 javascript 在 firebase 函数中从客户端获取 IP 地址。为什么我需要IP?制作可以访问我的功能的白名单IP。
我的目标:通过 IP 地址访问我的功能
我尝试使用此方法但对我不起作用它给了我 'undefined' :
exports.getIP = functions.https.onRequest(async (req, res) => {
var call = req.ip
console.log(call);
res.send(call);
});
exports.getIP = functions.https.onRequest(async (req, res) => {
var call = req.headers['x-forwarded-for']
console.log(call);
res.send(call);
});
这里当我调用 req.headers :
'x-forwarded-for'
和 x-appengine-user-ip
header 都将在您部署云函数时添加。您似乎正在使用在本地主机上运行的 Firebase Functions 模拟器(因为 host header 是 localhost:5001
)。您可以尝试部署该功能并记录 IP。
The
X-Forwarded-For
(XFF) header is a de-facto standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer.
The
X-Appengine-User-IP
is set by App Engine.
当您在本地模拟函数时,两者之间没有代理,因此缺少 header。
参考文献: