nuxt.js - 如何在 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,请查看本讨论中描述的代码 - 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)
}
}
推荐阅读
- c++ - C++ 输入处理
- javascript - 我应该以什么日期格式存储在 Firestore 中以创建每月的动态报告?
- javascript - 警报框无法显示所下订单的可变订单 ID
- html - 始终在页面上居中标题、输入和提交按钮
- javascript - Javascript 可以将整数视为数组吗?
- java - 使用java servlet时SQL错误无效列
- javascript - 如何在 javascript 中生成 3 个不同(唯一)的数字?
- node.js - 为相同的登录请求获取 3 个输出
- html - 随着半径的增加,如何实现边框变亮?
- google-admin-sdk - Google Drive 的 Google admin sdk 不返回最新结果