nginx+koa2 获取代理地址失败问题

nginx+koa2 获取代理地址失败问题

解决nginx代理接口后,koa2获取客户端ip,返回undefined问题

nginx配置

代理的路由需要转发之后,才能通过koa去获取到相应信息。
核心配置内容:
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;

http{
	...more http config
	server{
		...more server config
		location /api/ {     
	       rewrite /api/(.*) /$1 break;
	       proxy_pass http://127.0.0.1:8006;
	       proxy_set_header X-Forwarded-For $remote_addr;
	       proxy_set_header X-Real-IP $remote_addr;
	    }
	}
}

koa中获取ip地址

niginx代理后,需要转发之后才能获取

const ip = ctx.request.headers["x-forwarded-for"] ||
      ctx.request.headers["x-real-ip"] ||
      ctx.request.connection?.remoteAddress;

还是获取不到,可以尝试开启代理模式

// app.js
const Koa = require("koa");
const app = new Koa();
app.proxy = true;

解析ip地址的方法

通过高德提供的api解析

// key需要通过高德开放平台获取
const url  = `https://restapi.amap.com/v3/ip?ip=${ip}&key=${key}`
const res = await axios.get(url);

相关链接

获取高德key:link
ip地址解析:link

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值