最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I get the IP of a user in Nuxt's asyncData method? - Stack Overflow

programmeradmin7浏览0评论

Nuxt uses asyncData to run code server-side and then merges it with the data object.

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.

How can I access the calling user's IP address server-side instead of client-side?

Nuxt uses asyncData to run code server-side and then merges it with the data object.

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.

How can I access the calling user's IP address server-side instead of client-side?

Share Improve this question asked Aug 3, 2019 at 3:16 dsp_099dsp_099 6,12120 gold badges78 silver badges131 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

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 ma separated IPs if a call has passed through additional proxys (if there is multiple entries, then the client is the first one).

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;

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)
    }
  }

There was a github thread about this which makes grabbing the IP trivial in both environments (locally, production)

const ip = req.connection.remoteAddress || req.socket.remoteAddress

But be aware that you'll need to ensure the proxy headers are forwarded correctly. Because nuxt runs behind a traditional web server, without having the proxy headers forwarded, you'll always get the Local IP of the web server (127.0.0.1 unless loop back was changed).

发布评论

评论列表(0)

  1. 暂无评论