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

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

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

【问题讨论】:

    标签: node.js websocket apollo apollo-server graphql-subscriptions


    【解决方案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,我不知道如何修复它。无论如何感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2011-07-15
    相关资源
    最近更新 更多