如何使用 NginX + Next.JS + Apollo GraphQL 获取用户的 IP 地址
How can I get user's IP address using NginX + Next.JS + Apollo GraphQL
我正在使用 next.js 应用程序、graphql 服务器和 nginx。
我必须 grep 客户端 ip 地址。
所以在我的 nginx conf 文件中,我添加了
...
location / {
proxy_pass http://localhost:3000; # next.js server (3000)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /graphql {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:4000/graphql; # graphql server (4000)
}
并且在我的 graphql 中,我添加了
const ip = context.req.header('X-Real-IP')
console.log(ip)
现在我可以很好的获取客户端IP了!
但是,问题出在用户执行 SSR(刷新页面)时
IP地址是127.0.0.1 or localhost
即使用户在服务器端渲染,我怎么能得到真实的IP地址?
看起来您的 Next.js 进行了服务器到服务器的调用,因此您获得了本地主机 IP。
您需要将在 Next.js 中获得的用户 ip 附加到它向 GQL 服务器发出的请求。
我正在使用 next.js 应用程序、graphql 服务器和 nginx。
我必须 grep 客户端 ip 地址。
所以在我的 nginx conf 文件中,我添加了
...
location / {
proxy_pass http://localhost:3000; # next.js server (3000)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /graphql {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://localhost:4000/graphql; # graphql server (4000)
}
并且在我的 graphql 中,我添加了
const ip = context.req.header('X-Real-IP')
console.log(ip)
现在我可以很好的获取客户端IP了!
但是,问题出在用户执行 SSR(刷新页面)时
IP地址是127.0.0.1 or localhost
即使用户在服务器端渲染,我怎么能得到真实的IP地址?
看起来您的 Next.js 进行了服务器到服务器的调用,因此您获得了本地主机 IP。
您需要将在 Next.js 中获得的用户 ip 附加到它向 GQL 服务器发出的请求。