我对apollo-server上下文有疑问。我写了以下代码:
const { ApolloServer } = require("apollo-server-azure-functions");
const { typeDefs, resolvers } = require('../graphql_schema/schema');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
console.log(req);
return {
req: req
}
},
introspection: false,
playground: true,
});
module.exports = server.createHandler();
但是req变量始终是未定义的。 有人有主意吗?
我正在使用以下版本的阿波罗
"apollo-server": "^2.4.2",
"apollo-server-azure-functions": "^2.4.2",
非常感谢您。
答案 0 :(得分:1)
我有解决问题的方法。
上下文:({req})=> ... 一定是 上下文:(req)=> ...
const { ApolloServer } = require("apollo-server-azure-functions");
const { typeDefs, resolvers } = require('../graphql_schema/schema');
const server = new ApolloServer({
typeDefs,
resolvers,
context: (req) => {
return {
accesstoken: GetAccessToken(req.request)
}
},
introspection: false,
playground: true,
});
const GetAccessToken = function (request){
const token = (request.headers.authorization || '').replace('BEARER ', '');
return token;
}
module.exports = server.createHandler();
答案 1 :(得分:0)
需要在顶部定义req参数
const { ApolloServer } = require("apollo-server-azure-functions");
const { typeDefs, resolvers } = require('../graphql_schema/schema');
const server = new ApolloServer({
typeDefs,
resolvers,
req,
context: ({ req }) => {
console.log(req);
return {
req: req
}
},
introspection: false,
playground: true,
});
module.exports = server.createHandler();