问题描述
我想知道如何在 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.
proxy: {
'/api/': {
target: process.browser ? '' : 'http://localhost:3001','/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)
}
}