首页 > 解决方案 > 如何在 Nuxt.js 中获取客户端 IP 地址?

问题描述

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

标签: nuxt.jsip-address

解决方案


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

推荐阅读