Express 如何在ApolloServer中添加响应头?
我正在使用graphql ApolloServer,并将以下内容用于ApolloServerExpress 如何在ApolloServer中添加响应头?,express,graphql,apollo-server,Express,Graphql,Apollo Server,我正在使用graphql ApolloServer,并将以下内容用于ApolloServer server.applyMiddleware({ app, path: '/graphql' }); 我需要在响应头中传递解析程序返回的错误 我仔细阅读了这些文档,但看起来我们无法在上述中间件之后添加另一个中间件 我还尝试在初始化服务器时添加formatResponse,但这里的对象不是实际的http响应,我可以在其中更改错误头 const server = new ApolloServer({
server.applyMiddleware({ app, path: '/graphql' });
我需要在响应头中传递解析程序返回的错误
我仔细阅读了这些文档,但看起来我们无法在上述中间件之后添加另一个中间件
我还尝试在初始化服务器时添加formatResponse,但这里的对象不是实际的http响应,我可以在其中更改错误头
const server = new ApolloServer({
schema,
validationRules: [depthLimit(7)],
playground: process.env.NODE_ENV !== 'production',
debug: process.env.NODE_ENV !== 'production',
formatError: err => {
// Don't give the specific errors to the client.
if (err.message.startsWith('Database Error: ') || err.message.startsWith('connect')) {
return new Error('Internal server error');
}
// Otherwise return the original error. The error can also
// be manipulated in other ways, so long as it's returned.
return err;
},
formatResponse: (res:any,options:any) => {
// can't set headers here as it is not the http response object.
return res;
}
});
有什么办法可以做到这一点吗
const buildContext = async ({ res, req }) =>
// Attach additional properties to context if needed
({
user: req.user,
res,
req
});
与“apollo server express”集成包配合使用
import { ApolloServer } = 'apollo-server-express';
...
const server = new ApolloServer({
// schema, etc...
context: ({ res, req }) => buildContext({ res, req }),
formatResponse: (response, query ) => {
const { context } = query;
const { res, req: request } = context; // http response and request
// now you can set http response headers
// res.set(...)
const { data } = response; // graphql response's data
const { headers = {} } = request; // http request headers
return response; // graphql response
},
});
参考资料:虽然这段代码可以解决这个问题,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,而这些人可能不知道您的代码建议的原因。实际上,我仍然不理解这一点,如何设置变异的“值”?为什么请求未定义?我已经更新了答案,指定还需要手动将请求添加到apollo服务器上下文处理程序的上下文中。
new ApolloServer({
context: ({res}) => {
res.header('key', 'value')
}
})