如何在 Nuxt 的 asyncData 方法中获取用户的 IP?
How do I get the IP of a user in Nuxt's asyncData method?
Nuxt 使用 asyncData 运行 编码服务器端,然后将其与数据对象合并。
我想拨打一个需要知道用户IP的电话。 I see that I can get to the req
object which does have it but it's buried deep, deep 在那里,我担心这不是一个可靠的方法。
如何在服务器端而不是客户端访问调用用户的 IP 地址?
有一个关于此的 github 线程,这使得在两种环境(本地、生产)中获取 IP 变得微不足道
const ip = req.connection.remoteAddress || req.socket.remoteAddress
但请注意,您需要确保正确转发代理 headers。因为 nuxt 在传统的网络服务器后面运行,没有代理 headers 转发,你将始终获得网络服务器的本地 IP(127.0.0.1 除非环回被更改)。
如果nuxt运行在nginx等代理后面,那么你可以通过读取x-real-ip或x-forwarded-for在asyncData中获取客户端的IP地址。请注意,如果调用已通过其他代理(如果有多个条目,则客户端是第一个),x-forwarded-for 可以包含逗号分隔的 IP。
确保在您的 nginx 站点配置中设置 headers
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
然后你可以读取asyncData中的headers:
async asyncData(context) {
if (process.server) {
const req = context.req
const headers = (req && req.headers) ? Object.assign({}, req.headers) : {}
const xForwardedFor = headers['x-forwarded-for']
const xRealIp = headers['x-real-ip']
console.log(xForwardedFor)
console.log(xRealIp)
}
}
Nuxt 使用 asyncData 运行 编码服务器端,然后将其与数据对象合并。
我想拨打一个需要知道用户IP的电话。 I see that I can get to the req
object which does have it but it's buried deep, deep 在那里,我担心这不是一个可靠的方法。
如何在服务器端而不是客户端访问调用用户的 IP 地址?
有一个关于此的 github 线程,这使得在两种环境(本地、生产)中获取 IP 变得微不足道
const ip = req.connection.remoteAddress || req.socket.remoteAddress
但请注意,您需要确保正确转发代理 headers。因为 nuxt 在传统的网络服务器后面运行,没有代理 headers 转发,你将始终获得网络服务器的本地 IP(127.0.0.1 除非环回被更改)。
如果nuxt运行在nginx等代理后面,那么你可以通过读取x-real-ip或x-forwarded-for在asyncData中获取客户端的IP地址。请注意,如果调用已通过其他代理(如果有多个条目,则客户端是第一个),x-forwarded-for 可以包含逗号分隔的 IP。
确保在您的 nginx 站点配置中设置 headers
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
然后你可以读取asyncData中的headers:
async asyncData(context) {
if (process.server) {
const req = context.req
const headers = (req && req.headers) ? Object.assign({}, req.headers) : {}
const xForwardedFor = headers['x-forwarded-for']
const xRealIp = headers['x-real-ip']
console.log(xForwardedFor)
console.log(xRealIp)
}
}