在编写 Apollo Node.js 服务器时,可以通过 req
对象获取查询参数。下面是一个示例代码,展示如何在编写插件时获取查询参数:
const { ApolloServer, gql } = require('apollo-server');
const express = require('express');
// 定义 GraphQL schema
const typeDefs = gql`
type Query {
hello(name: String): String
}
`;
// 定义 GraphQL resolvers
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}!`,
},
};
// 创建 Apollo 服务器
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
{
// 定义插件
requestDidStart: (requestContext) => {
// 获取查询参数
const queryParams = requestContext.request.http?.headers.get('query-params');
console.log('Query Params:', queryParams);
return {
// 可以添加其他插件生命周期钩子函数
};
},
},
],
});
// 创建 Express 应用
const app = express();
// 将 Apollo 服务器应用于 Express 应用
server.applyMiddleware({ app });
// 启动服务器
app.listen({ port: 4000 }, () =>
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);
在上面的代码中,我们定义了一个 Apollo 服务器,并使用 plugins
属性添加了一个自定义插件。在插件的 requestDidStart
生命周期钩子函数中,我们可以通过 requestContext.request.http.headers
获取到所有的请求头信息,包括查询参数。
注意,这里使用了可选链操作符 ?.
来处理可能不存在的属性。这是因为 requestContext.request.http
对象只在使用 HTTP 协议时才会存在。如果你正在使用其他协议,可能需要根据实际情况修改代码。
当你启动服务器并发送带有查询参数的请求时,插件会输出查询参数的值。