如何在App-Engine上运行的基于Express的Node JS应用中获取远程客户端的IP地址 [英] How to get remote client's IP address in an express based Node JS app running on App-Engine
问题描述
在尝试获取IP时,所有标准标头值都包含不正确的值.
While trying to get IP, all standard headers values contain incorrect value.
req.ip: ::ffff:172.17.0.5
req.headers['x-forwarded-for']: 169.254.160.2
req.socket.remoteAddress: ::ffff:172.17.0.5
所有这些都会导致IP错误.
All of these result in wrong ip.
推荐答案
解决方案:
- 使用
let ip = req.headers['x-appengine-user-ip']
或 - 通过
app.set('trust proxy', true);
Express的信任代理设置>
- Either use
let ip = req.headers['x-appengine-user-ip']
or - Use Express's trust proxy settings by using
app.set('trust proxy', true);
说明: https://cloud.google.com/appengine /docs/flexible/nodejs/runtime#https_and_forwarding_proxies
App Engine在负载均衡器处终止HTTPS连接,并将请求转发到您的应用程序. 用户的IP地址在标准
X-Forwarded-For
标头和X-Appengine-User-Ip
标头中都可用.需要此信息的应用程序应配置其Web框架以信任代理.
App Engine terminates the HTTPS connection at the load balancer and forwards the request to your application. The user's IP address is available in the standard
X-Forwarded-For
header as well as theX-Appengine-User-Ip
header. Applications that require this information should configure their web framework to trust the proxy.
每个请求的标头值的完整列表:
Complete list of header values for each request:
{
"host": "<APP_ID>.appspot.com",
"x-real-ip": "169.254.160.2",
"x-forwarded-for": "169.254.160.2",
"x-google-real-ip": "169.254.160.2",
"x-appengine-user-ip": "2620:0:1002:100a:2c4b:4f6b:7851:a9d9",
"x-appengine-api-ticket": "aad4544d4e04a1a0",
"x-appengine-user-email": "",
"x-appengine-auth-domain": "gmail.com",
"x-appengine-user-id": "",
"x-appengine-user-nickname": "",
"x-appengine-user-organization": "",
"x-appengine-user-is-admin": "0",
"x-appengine-request-id-hash": "A104B85B",
"x-appengine-request-log-id": "5748c500ff00ff09eec9a104b85b0001737e736d6172742d737061726b2d39333632320001323031363035323774313530323538000100",
"x-appengine-https": "on",
"x-appengine-datacenter": "us6",
"x-appengine-default-version-hostname": "smart-spark-93622.appspot.com",
"cache-control": "max-age=0",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests": "1",
"save-data": "on",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36",
"accept-language": "en-US,en;q=0.8",
"x-appengine-country": "US",
"x-appengine-region": "ca",
"x-appengine-city": "san francisco",
"x-appengine-citylatlong": "37.774929,-122.419416",
"x-cloud-trace-context": "4a77265a7fa3e11be8cccebce59f7702/9314487514850703289;o=5"
}
可以看到,x-forwarded-for
被设置为x-google-real-ip
.因此,用户的ip现在在x-appengine-user-ip
中可用.
As one can see, x-forwarded-for
is being set as x-google-real-ip
. So user's ip is now available in x-appengine-user-ip
.
这篇关于如何在App-Engine上运行的基于Express的Node JS应用中获取远程客户端的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!