在Koa.js获取客户端IP
我有一个像这样的处理程序的Koa应用程序:
router.get('/admin.html', function *(next) { const clientIP = "?"; this.body = `Hello World ${clientIp}`; });
我需要获取客户端的IP地址来形成响应。 如何分配clientIp
,使其指向请求源的IP地址。
Koa 1:
假设你没有反向代理,你可以像这样使用this.request.ip
:
router.get('/admin.html', function *(next) { const clientIP = this.request.ip; this.body = `Hello World ${clientIP}`; });
请求文档中logging了此function。 你可以随时访问这个request
对象this.request
。
如果您有反向代理,您将始终获得反向代理的IP地址。 在这种情况下,这更加棘手:在反向代理configuration中,您需要添加一个特殊的头,例如X-Orig-IP
与原始客户端IP。
然后,你可以在koa访问它:
const clientIp = this.request.headers["X-Orig-IP"];
Koa 2:
方法非常相似,只是语法略有不同:
router.get('/', async (ctx, next) => { const clientIP = ctx.request.ip; ctx.body = `Hello World ${clientIP}`; })
如果你添加app.proxy=true
你仍然可以使用request.ip
而不必担心IP头。