【问题标题】:How can I get client IP address in Nuxt.js?如何在 Nuxt.js 中获取客户端 IP 地址?
【发布时间】:2021-07-10 03:34:20
【问题描述】:

我想知道如何在 Nuxt.js 中获取客户端 IP 地址。 我在客户端使用 Nuxt.js,在服务器端使用 Express。 我以为当服务器端收到请求时,我可以通过req.connection.remoteAddress req.headers['x-forwarded-for'].split(',').pop() 在服务器端获取客户端IP 地址。 但是,通过上面的代码,我只能得到::ffff:127.0.0.1

我google发现如果我使用nginx,我可以通过设置文件设置x-forwarded-for,但我没有使用nginx。 我可能正在使用@nuxtjs/proxy(但我不确定。对不起,我不太了解代理。)

modules: [
 '@nuxtjs/axios',
 '@nuxtjs/pwa',
 '@nuxtjs/proxy',
 '@nuxtjs/auth',
],
proxy: {
 '/api/': {
   target: process.browser ? '' : 'http://localhost:3001',
   pathRewrite: { '^/api/': '/' },
 },
}

nuxt.config.js的一部分。)

通过阅读@nuxtjs/proxy的文档,似乎可以设置'x-forwarded-for'标头,但我不知道如何获取客户端IP地址,我无法设置标头。

作为另一种方式,我尝试将客户端IP地址设置为参数,并使用以下代码。

client side

if (process.browser) {
  const ip = await this.$axios.$get('/ip/')
}
// send an request with this ip as a parameter.

nuxt.config.js

proxy: {
    '/api/': {
      target: process.browser ? '' : 'http://localhost:3001',
      pathRewrite: { '^/api/': '/' },
    },
    '/ip/': {
      target: process.browser ? 'http://icanhazip.com' : 'http://icanhazip.com',
      pathRewrite: { '^/ip/': '/' },
    },
  },

但我只能得到相同的,服务器端,全局 IP 地址,虽然我使用了process.browser

请帮我在 Nuxt.js 中获取客户端 IP 地址。 谢谢。

【问题讨论】:

  • 这是您要找的吗? stackoverflow.com/questions/57335203/…
  • 感谢您的重播。我会检查它是否有效。
  • 很抱歉,您教给我的解决方案不起作用。我得到的所有ip都是undefined。在解决方案中,使用了 nginx,并编写了一些设置来设置 headers。但我只是使用@nuxtjs/proxy,我没有(知道如何)编写这样的设置。
  • 我已经更新了我的答案,感谢您的详细反馈。

标签: nuxt.js ip-address


【解决方案1】:

对于 Nuxt 签出本讨论中描述的代码 - https://github.com/nuxt/nuxt.js/issues/2914

基本上,这个想法是将客户端 IP 存储在代理收到的请求中

export default ({ req, store }) => {
  if (process.server) {
    // https://github.com/nuxt/nuxt.js/issues/2914
    const ip = req.connection.remoteAddress || req.socket.remoteAddress
    store.commit('SET_IP', ip)
  }
  if (process.client) {
    localStorage.setItem('ip', store.getters.ip)
  }
}

【讨论】:

  • 非常感谢您的回答。很抱歉,我没有使用nginx。我只是使用@nuxtjs/proxy。你的意思是通过使用@nuxtjs/proxy(或Nuxt.js),我使用nginx?在那种情况下,我怎样才能找到proxy.conf?我只能在我的nuxt项目中找到nuxt.config.js
  • 我已经更新了我的答案,感谢您的详细反馈。
  • 感谢您的帮助!我可以通过您的代码获取 IP 地址。之后,通过添加app.$axios.defaults.headers.common.ip = store.getters.ip,我可以在标题中设置IP地址。
猜你喜欢
  • 2012-03-14
  • 2012-02-16
  • 2019-01-14
  • 2021-10-22
  • 1970-01-01
相关资源
最近更新 更多