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

API参考:expressMiddleware


此API参考文档了 4的 Express集成,the expressMiddleware函数。

expressMiddleware

注意

以下示例中,我们使用顶层 await 调用来异步启动我们的服务器。如果您想了解如何设置,请查看 入门指南 以获取详细信息。

函数 expressMiddleware 允许您将 Apollo Server 连接到 Express 服务器。

函数 expressMiddleware 预期您为您的 веб 框架设置 HTTP 请求体解析和 CORS 头部。具体来说,您可以使用 Express 本地的 express.json() 函数(自 Express v4.16.0 开始)和 cors 包来设置您的 Express 应用程序,如下所示。

有关配置项目的 CORS 行为的指导,请参阅 配置 CORS

函数 expressMiddleware 接受两个 。第一个 必需的 是一个 ApolloServer 实例,该实例通过调用其 start 方法已启动:

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import cors from 'cors';
import express from 'express';
const app = express();
const server = new ApolloServer<MyContext>({
typeDefs,
resolvers,
});
// Note you must call `start()` on the `ApolloServer`
// instance before passing the instance to `expressMiddleware`
await server.start();
// Specify the path where we'd like to mount our server
app.use('/graphql', cors<cors.CorsRequest>(), express.json(), expressMiddleware(server));
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import cors from 'cors';
import express from 'express';
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Note you must call `start()` on the `ApolloServer`
// instance before passing the instance to `expressMiddleware`
await server.start();
// Specify the path where we'd like to mount our server
app.use('/graphql', cors(), express.json(), expressMiddleware(server));

⚠️ 为确保您的服务器平稳关闭,我们建议您使用 ApolloServerPluginDrainHttpServer 插件。下面是一个示例。

expressMiddleware 函数的第二个可选 对象 用于配置 ApolloServer,它可以包含以下选项:

名称 /
类型
描述
上下文

函数

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

context 函数应该返回一个对象,该对象在执行一个 时所有服务器的 共享。这允许解析器共享有用的上下文值,例如数据库连接。

context 函数接收 reqres 选项,它们是 express.Requestexpress.Response 对象。

示例

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

// 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>(),
express.json(),
// 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(),
express.json(),
// 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/`);
上一页
startStandaloneServer
下一页
概述
评分文章评分在GitHub上编辑编辑论坛Discord

版权所有2024Apollo Graph Inc.,业务名称:Apollo GraphQL。

隐私政策

公司