获取 IP 地址作为字符串或空值

get the IP address as string or null value

我正在使用 NestJS 开发服务器应用程序。

我想获取客户端IP地址,因为客户端在代理服务器后面,我通过以下方式获取它的IP:

const theIp = request.headers['x-forwarded-for'];

但是上面theIp的return类型是string | string[] | undefined.

我希望 IP 地址为 string 值或 null。正确的做法是什么?我试过的是:

const clientIP = theIP? (theIp.length > 0? theIp[0]: null) : null;

但我不确定最后的结果是否可靠。有什么更好的方法可以将客户端 IP 地址作为字符串或空值获取?或者我的解决方案已经足够好了?

如果返回字符串,您的代码将无法按预期工作,因为 stringstring[] 的长度均为 属性。

更好的方法是使用 typeof:

const clientIP = typeof theIp === 'string' ? theIp : theIp?.length > 0 ? theIp[0] : null;

根据 ES2015 语法的要求进行编辑(可以编写 one-liner 但是重叠超过 2 个三元操作很难阅读和调试,所以我更喜欢写一个函数):

function getClientIp(theIp) {
  if (typeof theIp === 'string') return theIp;
  if (theIp === undefined || theIp.length <= 0) return null;
  return theIp[0];
}

请注意,下次您可以轻松地自行测试代码的行为方式,而无需在 SO 上发布问题 :)

function getClientIp(theIp) {
  return typeof theIp === 'string'
    ? theIp
    : theIp?.length > 0
    ? theIp[0]
    : null;
}

console.log(getClientIp('192.0.0.1')); // 192.0.0.1
console.log(getClientIp(['192.0.0.1'])); // 192.0.0.1
console.log(getClientIp([])); // null
console.log(getClientIp(undefined)); // null