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);