如何在 Nuxt 的 asyncData 方法中获取用户的 IP? [英] How do I get the IP of a user in Nuxt's asyncData method?
问题描述
Nuxt 使用 asyncData 在服务器端运行代码,然后将其与数据对象合并.
Nuxt uses asyncData to run code server-side and then merges it with the data object.
我想拨打电话,要求我知道用户的 IP.我看到我可以访问 req
对象,它确实有它但它被埋在很深很深,我担心这不是一种可靠的方法.
I want to make a call that requires me to know the user's IP. I see that I can get to the req
object which does have it but it's buried deep, deep in there and I worry this is not a reliable way of doing it.
如何在服务器端而不是客户端访问主叫用户的 IP 地址?
How can I access the calling user's IP address server-side instead of client-side?
推荐答案
如果 nuxt 运行在 nginx 等代理之后,那么您可以通过读取 x-real-ip 或 x-forwarded- 在 asyncData 中获取客户端的 IP 地址-为了.请注意,如果调用通过了额外的代理,则 x-forwarded-for 可以包含逗号分隔的 IP(如果有多个条目,则客户端是第一个).
If nuxt is running behind a proxy such as nginx, then you can get the client's IP address in asyncData by reading x-real-ip or x-forwarded-for. Be aware that x-forwarded-for can contain comma separated IPs if a call has passed through additional proxys (if there is multiple entries, then the client is the first one).
确保在您的 nginx 站点配置中设置标头
Make sure to set up the headers in your nginx site configuration
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 中的头信息:
Then you can read the headers in asyncData:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!