Firebase功能:如何从客户端获取IP地址?

Kha*_*tri 1 javascript node.js firebase google-cloud-functions

我正在尝试使用 javascript 从 firebase 函数中的客户端获取 IP 地址。为什么我需要IP?将可以访问我的功能的IP列入白名单。

我的目标: 通过 IP 地址访问我的功能

我尝试使用此方法,但对我不起作用,它给了我“未定义”:

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);
  });
Run Code Online (Sandbox Code Playgroud)

当我调用 req.headers 时:

在此输入图像描述

Dha*_*raj 5

当您部署云函数时,将添加'x-forwarded-for'和标头。x-appengine-user-ip看来您正在使用在 localhost 上运行的 Firebase Functions 模拟器(因为主机标头是localhost:5001)。您可以尝试部署该功能并记录IP。

(XFF)标X-Forwarded-For头是事实上的标准标头,用于识别通过HTTP 代理或负载均衡器连接到 Web 服务器的客户端的原始 IP 地址。

X-Appengine-User-IP由 App Engine 设置。

当您在本地模拟函数时,中间没有代理,因此这些标头丢失。

参考: