在Koa.js中获取客户端IP

Uli*_*ler 4 javascript node.js koa

我有一个像这样的处理程序的Koa应用程序:

router.get('/admin.html', function *(next) {
    const clientIP = "?";
    this.body = `Hello World ${clientIp}`;
});
Run Code Online (Sandbox Code Playgroud)

我需要获取客户端的IP地址以形成响应.我如何分配,clientIp以便它引用请求所源自的IP地址.

Uli*_*ler 10

Koa 1:

假设你没有反向代理,你可以this.request.ip像这样使用:

router.get('/admin.html', function *(next) {
    const clientIP = this.request.ip;
    this.body = `Hello World ${clientIP}`;
});
Run Code Online (Sandbox Code Playgroud)

请求文档中记录了此功能.您始终可以访问所述request对象this.request.

如果您有反向代理,您将始终获得反向代理的IP地址.在这种情况下,它更棘手:在反向代理配置中,您需要添加一个特殊的标头,例如X-Orig-IP使用原始客户端IP.

然后,您可以在koa访问它:

const clientIp = this.request.headers["X-Orig-IP"];
Run Code Online (Sandbox Code Playgroud)

Koa 2:

方法非常相似,只是语法略有不同:

router.get('/', async (ctx, next) => {
    const clientIP = ctx.request.ip;
    ctx.body = `Hello World ${clientIP}`;
})
Run Code Online (Sandbox Code Playgroud)


Ido*_*o.S 5

如果添加, app.proxy=true 您仍然可以使用,request.ip而不必担心 IP 标头。


小智 5

我遇到了同样的问题,但通过使用 NPM 上找到的这个模块解决了它 request-ip

在 koa 中可以简单地使用userIp = requestIp.getClientIp(ctx.request)

用户ip按以下顺序确定:

X-Client-IP
X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
CF-Connecting-IP (Cloudflare)
Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
True-Client-Ip (Akamai and Cloudflare)
X-Real-IP (Nginx proxy/FastCGI)
X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
req.connection.remoteAddress
req.socket.remoteAddress
req.connection.socket.remoteAddress
req.info.remoteAddress
Run Code Online (Sandbox Code Playgroud)

如果找不到 IP 地址,则返回 null。