Javascript req.user未定义,即使它能够对用户进行console.log操作
我正在尝试使用JWT在Graphql中实现身份验证。我有一个函数,该函数假定可以获取给定令牌的用户信息。它应该返回用户,以便我可以在Graphql查询中使用它 当我尝试发出post请求时,它返回为nullJavascript req.user未定义,即使它能够对用户进行console.log操作,javascript,mongoose,jwt,schema,graphql,Javascript,Mongoose,Jwt,Schema,Graphql,我正在尝试使用JWT在Graphql中实现身份验证。我有一个函数,该函数假定可以获取给定令牌的用户信息。它应该返回用户,以便我可以在Graphql查询中使用它 当我尝试发出post请求时,它返回为null const addUser = async (req) => { const token = req.headers.authorization; try { const { user } = await jwt.verify(token, SECRET);
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);
控制台是这样说的
用户:req.user
ReferenceError:未定义req
我不明白为什么,因为我已经将req.user设置为与user相等的user您似乎使用了
express graphql
,请查看文档:
您以错误的方式使用graphqlHTTP
中间件
请看下面的代码:
app.use('/graphql',graphqlHTTP(异步(请求、响应、graphQLParams)=>({
模式:MyGraphQLSchema,
rootValue:wait someFunctionToGetRootValue(请求),
graphiql:对
})));
您应该将带有
req
参数的函数传递到graphqlHTTP
中间件。无论您在第一段代码中做了什么,第二个函数不知道什么是req
。那么我如何才能使第二个函数知道什么是req.user呢?请检查本文结尾的示例:我阅读了它,看到了示例,但我如何在代码中实现这一点?老实说,我不确定如何回答这个问题。这个网站不是一个获得免费的分步教程的地方。
app.use("/graphql", graphqlHTTP({
schema,
graphiql: true,
context: {
user: req.user,
SECRET
}
}))