我正在使用graphql ApolloServer,并对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;
}
});
是否有任何选项可以做到这一点?
答案 0 :(得分:3)
new ApolloServer({
context: ({res}) => {
res.header('key', 'value')
}
})
参考:https://www.apollographql.com/docs/apollo-server/api/apollo-server/
答案 1 :(得分:0)
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
};