如何在 apollo 订阅服务器上获取客户端 IP 地址?

Posted

技术标签:

【中文标题】如何在 apollo 订阅服务器上获取客户端 IP 地址?【英文标题】:How to get client ip address on an apollo subscriptions server? 【发布时间】:2020-07-11 06:40:36 【问题描述】:

如何在 apollo 订阅服务器上获取客户端的 ip 地址?

它是否包含在.onConnect 方法here 的任何地方

【问题讨论】:

【参考方案1】:

您可以使用context.request.connection.remoteAddress获取客户端的IP地址。

例如

import http from 'http';
import  ApolloServer, gql, PubSub  from 'apollo-server-express';
import express from 'express';

const pubsub = new PubSub();
const POST_ADDED = 'POST_ADDED';
const db:  posts: any[]  = 
  posts: [],
;

const typeDefs = gql`
  type Subscription 
    postAdded: Post
  

  type Query 
    posts: [Post]
  

  type Mutation 
    addPost(author: String, comment: String): Post
  

  type Post 
    author: String
    comment: String
  
`;
const resolvers = 
  Subscription: 
    postAdded: 
      subscribe: () => pubsub.asyncIterator([POST_ADDED]),
    ,
  ,
  Query: 
    posts(root, args, context) 
      return db.posts;
    ,
  ,
  Mutation: 
    addPost(root, args, context) 
      pubsub.publish(POST_ADDED,  postAdded: args );
      const post =  ...args ;
      db.posts.push(post);
    ,
  ,
;

const PORT = 4000;
const app = express();
const server = new ApolloServer(
  typeDefs,
  resolvers,
  subscriptions: 
    onConnect: (connectionParams, webSocket, context) => 
      console.log('remote address: ', context.request.connection.remoteAddress);
      console.log('websocket connected');
    ,
    onDisconnect: (webSocket, context) => 
      console.log('websocket disconnected');
    ,
  ,
);

server.applyMiddleware( app );

const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen(PORT, () => 
  console.log(`? Server ready at http://localhost:$PORT$server.graphqlPath`);
  console.log(`? Subscriptions ready at ws://localhost:$PORT$server.subscriptionsPath`);
);

调试日志:

? Server ready at http://localhost:4000/graphql
? Subscriptions ready at ws://localhost:4000/graphql
remote address:  ::1
websocket connected

我用localhost测试,所以客户端IP地址是::1::1 是“IPv6 中的环回地址”,又名 localhost。

【讨论】:

不幸的是,我从服务器得到的是 ::ffff:127.0.0.1,我不知道如何修复它。无论如何感谢您的帮助

以上是关于如何在 apollo 订阅服务器上获取客户端 IP 地址?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Apollo 中关闭 GraphQL 订阅的套接字连接

使用 Express-GraphQL 和 React-Apollo 订阅 GraphQL

如何在 React 中为上传和订阅设置 Apollo 客户端?

如何在 jest / apollo 客户端中捕获被拒绝的 graphql 订阅?

如何使用 NginX + Next.JS + Apollo GraphQL 获取用户的 IP 地址

如何在 apollo 客户端中检测订阅(websocket)的断开和重新连接