【问题标题】:req.user is undefined even though it is able to console.log the userreq.user 是未定义的,即使它能够 console.log 用户
【发布时间】:2019-07-12 04:29:24
【问题描述】:

我正在尝试使用 JWT 在 Graphql 中实现身份验证。我有一个功能应该是获取给定令牌的用户信息。它应该返回用户,以便我可以在我的 Graphql 查询中使用它。

当我尝试发出一个 post 请求时,它返回为 null。

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 等于用户

【问题讨论】:

  • 不管你在第一段代码中做了什么,第二段代码都不知道req是什么。
  • 那么我怎样才能让第二个函数知道 req.user 是什么
  • 查看本文末尾的示例:github.com/graphql/express-graphql#options
  • 我阅读并看到了示例,但我将如何在我的代码中实现它
  • 说实话,我不知道如何回答。此网站不是获取免费分步教程的地方。

标签: javascript mongoose jwt schema graphql


【解决方案1】:

你好像用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 中间件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 2021-04-22
    • 2022-10-06
    • 2020-08-08
    • 1970-01-01
    • 2019-12-10
    • 2015-07-18
    • 2021-12-27
    相关资源
    最近更新 更多