加入我们,从10月8日至10日,在纽约市学习关于 GraphQL 联邦和 API 平台工程的最新技巧、趋势和新闻。加入我们,共同参加2024年纽约市的 GraphQL 峰会
文档
免费开始

API 参考:startStandaloneServer


本 API 参考文档描述了startStandaloneServer函数。

概述

startStandaloneServer函数帮助您快速入门。此函数适用于所有不需要支持或特定 Node.js 框架(如 Fastify)的项目。在底层,startStandaloneServer函数使用 Apollo Server 4 的 Express集成(即expressMiddleware)。

由于其设置了有用的默认值,此函数的配置性不如其他 Apollo Server集成。复杂的项目最终可能需要切换到使用 expressMiddleware(此过程简单直接)。

startStandaloneServer

注意

在下面的示例中,我们使用顶级await调用以异步方式启动服务器。如果您想了解我们如何设置此配置,请查阅开始指南以获取详细信息。

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:

选项

名称
类型
描述
context

Function

一个可选的异步 context 初始化函数

The context function should return an object that all your server's share during an 's execution. This enables resolvers to share helpful context values, such as a database connection.

The context function receives req and res options which are http.IncomingMessage and http.ServerResponse types.

listen

Object

一个可选的 listen 配置对象。The listen 选项接受具有与 net.Server.listen 选项对象 相同属性的的对象。

如果没有指定 port,则默认使用 {port: 4000}

示例

下面是设置 startStandaloneServer 的完整示例:

// npm install @apollo/server graphql
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}`);
// npm install @apollo/server graphql
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

The startStandaloneServer 函数并不适用于所有用例,尤其是当你需要自定义服务器行为时。例如,你可能想要自定义 CORS 行为,在处理 请求之前运行一些中间件,或从同一服务器提供其他端点。

在这些情况下,我们建议您将 startStandaloneServer 替换为 expressMiddleware (除非您确信要使用不同的Node.js框架)。这个更改只需要几行,并且对服务器现有行为的影响最小(startStandaloneServer 在内部使用 expressMiddleware)。

我们推荐Express,因为它是最受欢迎的Node.js网络框架,并且与许多其他流行库集成良好。它确实有一些限制(例如,Express的异步支持不是基于 Promiseasync 函数),但是与较新的库相比,框架中的向后不兼容的更改更少。

示例

假设我们当前的 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 cors
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 cors from 'cors';
import { typeDefs, resolvers } from './schema';
interface MyContext {
token?: String;
}
// Required logic for integrating with Express
const 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 start
await 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 needs
express.json({ limit: '50mb' }),
// expressMiddleware accepts the same arguments:
// an Apollo Server instance and optional configuration options
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.token }),
}),
);
// Modified server startup
await 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 cors
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 cors from 'cors';
import { typeDefs, resolvers } from './schema';
// Required logic for integrating with Express
const 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 start
await 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 needs
express.json({ limit: '50mb' }),
// expressMiddleware accepts the same arguments:
// an Apollo Server instance and optional configuration options
expressMiddleware(server, {
context: async ({ req }) => ({ token: req.headers.token }),
}),
);
// Modified server startup
await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at https://127.0.0.1:4000/`);
Previous
ApolloServer
Next
expressMiddleware
Rate articleRate在GitHub编辑编辑论坛Discord

©2024Apollo Graph Inc.,即Apollo GraphQL。

隐私政策

公司