API 参考:startStandaloneServer
本 API 参考文档描述了startStandaloneServer
函数。
概述
此startStandaloneServer
函数帮助您快速入门Apollo Server。此函数适用于所有不需要无服务器支持或特定 Node.js 框架(如 Fastify)的项目。在底层,startStandaloneServer
函数使用 Apollo Server 4 的 Express集成(即expressMiddleware
)。
由于其设置了有用的默认值,此函数的配置性不如其他 Apollo Server集成。复杂的项目最终可能需要切换到使用 expressMiddleware
(此过程简单直接)。
startStandaloneServer
此startStandaloneServer
函数接受两个参数。第一个必需参数是开始监听输入请求的ApolloServer
实例:
import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';const server = new ApolloServer({ typeDefs, resolvers });// `startStandaloneServer` returns a `Promise` with the// the URL that the server is listening on.const { url } = await startStandaloneServer(server);
import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';const server = new ApolloServer({ typeDefs, resolvers });// `startStandaloneServer` returns a `Promise` with the// the URL that the server is listening on.const { url } = await startStandaloneServer(server);
The startStandaloneServer
function's second optional argument is an object for configuring your server's options, which can contain the following properties:
选项
名称 类型 | 描述 |
---|---|
| 一个可选的异步 The The |
| 一个可选的 如果没有指定 |
示例
下面是设置 startStandaloneServer
的完整示例:
// npm install @apollo/server graphqlimport { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';import { typeDefs, resolvers } from './schema';interface MyContext {token?: String;}const server = new ApolloServer<MyContext>({ typeDefs, resolvers });const { url } = await startStandaloneServer(server, {context: async ({ req }) => ({ token: req.headers.token }),listen: { port: 4000 },});console.log(`🚀 Server ready at ${url}`);
// npm install @apollo/server graphqlimport { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';import { typeDefs, resolvers } from './schema';const server = new ApolloServer({ typeDefs, resolvers });const { url } = await startStandaloneServer(server, {context: async ({ req }) => ({ token: req.headers.token }),listen: { port: 4000 },});console.log(`🚀 Server ready at ${url}`);
切换到 expressMiddleware
The startStandaloneServer
函数并不适用于所有用例,尤其是当你需要自定义服务器行为时。例如,你可能想要自定义 CORS 行为,在处理 GraphQL 请求之前运行一些中间件,或从同一服务器提供其他端点。
在这些情况下,我们建议您将 startStandaloneServer
替换为 expressMiddleware
(除非您确信要使用不同的Node.js框架)。这个更改只需要几行,并且对服务器现有行为的影响最小(startStandaloneServer
在内部使用 expressMiddleware
)。
我们推荐Express,因为它是最受欢迎的Node.js网络框架,并且与许多其他流行库集成良好。它确实有一些限制(例如,Express的异步支持不是基于 Promise
和 async
函数),但是与较新的库相比,框架中的向后不兼容的更改更少。
示例
假设我们当前的 startStandaloneServer
设置使用以下代码:
import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';import { typeDefs, resolvers } from './schema';interface MyContext {token?: String;}const server = new ApolloServer<MyContext>({ typeDefs, resolvers });const { url } = await startStandaloneServer(server, {context: async ({ req }) => ({ token: req.headers.token }),listen: { port: 4000 },});console.log(`🚀 Server ready at ${url}`);
import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';import { typeDefs, resolvers } from './schema';const server = new ApolloServer({ typeDefs, resolvers });const { url } = await startStandaloneServer(server, {context: async ({ req }) => ({ token: req.headers.token }),listen: { port: 4000 },});console.log(`🚀 Server ready at ${url}`);
要将使用更改为 expressMiddleware
,您首先需要安装以下包,以便您可以为服务器设置CORS:
npm install express cors
接下来,我们可以修改我们的代码以匹配以下
// npm install @apollo/server express graphql corsimport { 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 cors from 'cors';import { typeDefs, resolvers } from './schema';interface MyContext {token?: String;}// Required logic for integrating with Expressconst app = express();// Our httpServer handles incoming requests to our Express app.// Below, we tell Apollo Server to "drain" this httpServer,// enabling our servers to shut down gracefully.const httpServer = http.createServer(app);// Same ApolloServer initialization as before, plus the drain plugin// for our httpServer.const server = new ApolloServer<MyContext>({typeDefs,resolvers,plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});// Ensure we wait for our server to startawait server.start();// Set up our Express middleware to handle CORS, body parsing,// and our expressMiddleware function.app.use('/',cors<cors.CorsRequest>(),// 50mb is the limit that `startStandaloneServer` uses, but you may configure this to suit your needsexpress.json({ limit: '50mb' }),// expressMiddleware accepts the same arguments:// an Apollo Server instance and optional configuration optionsexpressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);// Modified server startupawait new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at https://127.0.0.1:4000/`);
// npm install @apollo/server express graphql corsimport { 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 cors from 'cors';import { typeDefs, resolvers } from './schema';// Required logic for integrating with Expressconst app = express();// Our httpServer handles incoming requests to our Express app.// Below, we tell Apollo Server to "drain" this httpServer,// enabling our servers to shut down gracefully.const httpServer = http.createServer(app);// Same ApolloServer initialization as before, plus the drain plugin// for our httpServer.const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});// Ensure we wait for our server to startawait server.start();// Set up our Express middleware to handle CORS, body parsing,// and our expressMiddleware function.app.use('/',cors(),// 50mb is the limit that `startStandaloneServer` uses, but you may configure this to suit your needsexpress.json({ limit: '50mb' }),// expressMiddleware accepts the same arguments:// an Apollo Server instance and optional configuration optionsexpressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);// Modified server startupawait new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at https://127.0.0.1:4000/`);