我正在尝试使用JWT在Graphql中实现身份验证。我有一个功能,该功能应该获取给定令牌的用户信息。它应该返回用户,以便我可以在我的Graphql查询中使用它。
当我尝试发出发布请求时,它返回为空。
const addUser = async (req) => {
const token = req.headers.authorization;
try {
const { user } = await jwt.verify(token, SECRET);
req.user = user;
} catch (err) {
console.log(err);
}
req.next();
};
app.use(addUser);
app.use("/graphql", graphqlHTTP({
schema,
graphiql: true,
context: {
user: req.user,
SECRET
}
}))
控制台说 用户:req.user,
ReferenceError:未定义req
我不明白为什么,因为我已经将req.user设置为等于该用户
答案 0 :(得分:0)
似乎您使用express-graphql
,看一下文档:https://github.com/graphql/express-graphql
您以错误的方式使用graphqlHTTP
中间件。
看看下面的代码:
app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
schema: MyGraphQLSchema,
rootValue: await someFunctionToGetRootValue(request),
graphiql: true
})));
您应将带有req
参数的函数传递到graphqlHTTP
中间件中。