[英]Get IP ADDRESS in Express and GraphQL
I have a question.我有个问题。 So, I recently switched from rest
to gql
, and I have a problem.所以,我最近从rest
切换到gql
,我遇到了问题。 In rest
I got ip address
by req.ip
.在rest
,我通过req.ip
获得了ip address
。 I tried to do it in resolve()
function and it wasn't working (undefined)
.我尝试在resolve()
function 中执行此操作,但没有成功(undefined)
。 I searched the web and found this:我搜索了 web 并找到了这个:
const server = new GraphQLServer({
context: context => ({
...context,
db,
userIp: maybeGetUserIpAddress(context.request),
}),
});
const maybeGetuserIpAddress = (request): ?string => {
const headers = request.headers;
if (!headers) return null;
const ipAddress = headers['x-forwarded-for'];
if (!ipAddress) return null;
return ipAddress;
};
But it returns undefined
too.但它也返回undefined
。
So, my questions are:所以,我的问题是:
1. Is this because I'm hosting my server locally?
2. What is wrong with the code
Yes it's because you are on localhost req.ip && req.socket.remoteAddress won't do the trick.是的,这是因为您在 localhost req.ip && req.socket.remoteAddress 上无法解决问题。
You can use this instead.您可以改用它。
(req -> express.Request) (req -> express.Request)
const ip = require('ipware')().get_ip(req)?.clientIp || req?.ip || req?.socket?.remoteAddress || '127.0.0.1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.