GraphQL 是一种强大的查询语言,用于 API 开发。以下是使用 Node.js + Express + Apollo Server 搭建 GraphQL 服务的步骤:


1. 初始化项目 📁

mkdir graphql-project && cd graphql-project
npm init -y
npm install express apollo-server graphql
GraphQL_服务器架构

2. 创建基本结构 🧱

// server.js
const express = require('express');
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello World!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
app.use('/graphql', server.getGraphQLHandler());
app.listen({ port: 4000 }, () => {
  console.log('GraphQL 服务运行在 http://localhost:4000/graphql');
});
GraphQL_查询语言

3. 测试服务 🧪

访问 http://localhost:4000/graphql 并尝试查询:

{
  hello
}
GraphQL_响应示例

4. 扩展阅读 📚

通过以上步骤,您已成功搭建基础 GraphQL 服务!🎉