使用 Apollo Server 可快速构建 Node.js GraphQL 服务器,先初始化项目并安装 express、apollo-server-express 和 graphql 依赖,接着定义 User 类型和查询的 schema,编写返回模拟数据的解析器,然后在 Express 应用中启动 Apollo Server 并监听端口,最后通过访问 /graphql 在 Playground 测试 users 和 user 查询,逐步可扩展功能至生产环境。

构建一个基于 Node.js 的 GraphQL API 服务器并不复杂。你可以使用 Express 搭配 graphql 和 express-graphql 来快速搭建,或者选择更现代的方案如 Apollo Server。下面以 Apollo Server 为例,一步步带你实现。
创建项目目录并初始化 npm:
mkdir my-graphql-server安装必要的依赖:
npm install express apollo-server-express graphql创建一个简单的用户查询示例。新建 index.js 文件:
先定义 schema(类型系统):
const { ApolloServer, gql } = require('apollo-server-express');然后编写解析器逻辑:
// 模拟数据继续在 index.js 中集成 Express 与 Apollo Server:
const express = require('express');运行服务:
node index.js打开浏览器访问 http://localhost:4000/graphql,即可使用 GraphQL Playground 测试接口。
在 Playground 中输入以下查询:
{ users { id name email } }你会得到 JSON 格式的用户列表响应。也可以按 ID 查询单个用户:
{ user(id: "1") { name email } } 基本上就这些。你可以逐步扩展 schema,加入 Mutation、认证、数据库连接等功能。Apollo Server 提供了良好的扩展性,适合从原型到生产环境的过渡。以上就是如何用Node.js构建一个GraphQL API服务器?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号