You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GraphQL Express服务器运行在IP地址而非localhost上

如何让GraphQL Express服务器运行在IP地址而非localhost上

别急,我来帮你搞定这个问题!你遇到的核心问题就是服务器默认只绑定了localhost,只有本机能访问,同一局域网的真机根本连不上。针对你用的Apollo Server v4 + Express的场景,按下面的步骤操作就可以解决:

第一步:修改Apollo Server的监听配置,绑定所有网络接口

原来的服务器启动代码可能只指定了端口,没有设置host参数,我们需要把host设为0.0.0.0——这个值表示监听机器上所有的网络接口,不管是WiFi还是有线连接,同一局域网的设备都能通过你的机器IP访问。

给你一个完整的启动代码示例,你可以对照修改你的index.js:

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import http from 'http';

async function startServer() {
  const app = express();
  const httpServer = http.createServer(app);

  // 初始化Apollo Server,这里替换成你自己的typeDefs和resolvers
  const server = new ApolloServer({
    typeDefs: /* 你的GraphQL类型定义 */,
    resolvers: /* 你的解析器函数 */,
  });

  await server.start();
  app.use('/graphql', expressMiddleware(server));

  // 关键改动:在这里指定host为0.0.0.0,端口保持你原来的(比如4000)
  await new Promise(resolve => httpServer.listen({ port: 4000, host: '0.0.0.0' }, resolve));
  
  // 这里记得把<你的局域网IP>换成你自己的真实IP,比如192.168.1.100
  console.log(`🚀 服务器启动成功,访问地址:http://<你的局域网IP>:4000/graphql`);
}

startServer();

怎么查自己的局域网IP?

  • Windows:打开命令提示符,输入ipconfig,找WiFi适配器对应的IPv4地址
  • Mac/Linux:打开终端,输入ifconfig或者ip addr,找WiFi接口的inet地址(比如192.168.x.x格式)

第二步:更新前端Expo项目的GraphQL客户端地址

前端原来的客户端配置里,URI肯定是http://localhost:4000/graphql,现在要改成你服务器的局域网IP地址,比如:

import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';

const httpLink = createHttpLink({
  // 替换成你的服务器IP和端口
  uri: 'http://192.168.1.100:4000/graphql',
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

⚠️ 注意:你的真机必须和服务器在同一个WiFi局域网下,不然还是连不上!

第三步:检查防火墙设置

有时候Windows防火墙或者Mac的安全设置会阻止外部设备访问你的4000端口,导致真机连不上。你可以临时关闭防火墙测试一下,如果能连上了,就给你的Node.js进程或者4000端口添加一个入站允许规则,这样不用一直关防火墙。

(可选)如果需要使用订阅功能的配置调整

如果你之后要加GraphQL订阅,Apollo Server v4需要用@apollo/server/plugin/subscriptions-transport-ws,配置的时候也要注意host的设置,给你一个参考示例:

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import express from 'express';
import http from 'http';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';

async function startServer() {
  const app = express();
  const httpServer = http.createServer(app);

  // 先创建可执行的schema
  const schema = makeExecutableSchema({
    typeDefs: /* 你的类型定义 */,
    resolvers: /* 你的解析器 */,
  });

  // 配置WebSocket服务器,这里也要注意host
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: '/graphql/subscriptions',
    host: '0.0.0.0',
  });
  const cleanupSubscriptionServer = useServer({ schema }, wsServer);

  // 初始化Apollo Server,添加清理插件
  const server = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await cleanupSubscriptionServer.dispose();
            },
          };
        },
      },
    ],
  });

  await server.start();
  app.use('/graphql', expressMiddleware(server));

  // 同样指定host为0.0.0.0启动服务器
  await new Promise(resolve => httpServer.listen({ port: 4000, host: '0.0.0.0' }, resolve));
  console.log(`🚀 服务器启动:http://192.168.1.100:4000/graphql`);
  console.log(`🚀 订阅地址:ws://192.168.1.100:4000/graphql/subscriptions`);
}

startServer();

按照这些步骤改完,你的真机应该就能正常连接到后端的GraphQL服务器,完成登录请求了。

备注:内容来源于stack exchange,提问作者pelotador.1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 09:48:02