我不能在我的Apollo-Server上访问每个HTTP请求中的"Authorization“头,这是用express实现的。这是我的express,Apollo-Server,CORS等的设置。
const corsConfig = {
credentials: true,
allowedHeaders: ['Authorization'],
exposedHeaders: ['Authorization']
};
const app = express()
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
req
};
}
});
server.applyMiddleware({
app,
path,
cors: corsConfig
});
http.createServer(app).listen(port, () => logger.info(`Service started on port ${port}`));在我的解析器中,我引入了上下文,特别是req对象(这是一个示例graphQL端点解析器):
const exampleQuery = async (parent, input , { req }) => {
console.log(req.headers);
/*
The output of this log:
{
'content-type': 'application/json',
accept: '*/*',
'content-length': '59',
'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)',
'accept-encoding': 'gzip,deflate',
connection: 'close',
host: 'localhost:3301',
'Access-Control-Allow-Headers': 'Authorization',
'Access-Control-Expose-Headers': 'Authorization'
}
*/
}我用一个"Authorization“头向这个端点发送了请求,其中包含一个令牌作为值。但是,Authorization不在req.headers对象中(事实上,它也不在整个req对象中)。我确信我对这个端点的Postman/Insomnia HTTP请求正在发送Authorization头,但是它似乎没有通过我的Apollo-Server。有人知道为什么Authorization头不能通过吗?
解决方案:
问题实际上是,我使用的是Apollo联合微服务体系结构,它需要在网关上进行额外的配置,以便将Authorization头传递到各个微服务,解析器所在的位置。您必须在ApolloGateway构造函数中添加buildService函数,在该构造函数中,您可以指定底层微服务的RemoteGraphQLDataSource willSendRequest of context.req.headers.authentication
发布于 2020-05-06 13:42:16
它按照预期工作,例如。
server.ts
import { ApolloServer, gql, makeExecutableSchema } from 'apollo-server-express';
import express from 'express';
import http from 'http';
const corsConfig = {
credentials: true,
allowedHeaders: ['Authorization'],
exposedHeaders: ['Authorization'],
};
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: (_, __, { req }) => {
console.log(req.headers);
return 'world';
},
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = express();
const path = '/graphql';
const port = 3000;
const server = new ApolloServer({
schema,
context: ({ req }) => {
return {
req,
};
},
});
server.applyMiddleware({ app, path, cors: corsConfig });
http.createServer(app).listen(port, () => console.info(`Service started on port ${port}`));通过curl发送GraphQL查询HTTP请求:
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer abc123" --data '{ "query": "{ hello }" }' http://localhost:3000/graphql
{"data":{"hello":"world"}}服务器端日志:
Service started on port 3000
{ host: 'localhost:3000',
'user-agent': 'curl/7.54.0',
accept: '*/*',
'content-type': 'application/json',
authorization: 'Bearer abc123',
'content-length': '24' }https://stackoverflow.com/questions/61601783
复制相似问题