node.js - typescript jwt.verify 无法访问数据

标签 node.js typescript jwt

我正在尝试将 JWT 与 Node.js 一起使用。 我的问题是我无法从 JWT 验证功能读取数据。 我这样使用它:

//encode when logging in
const token = jwt.sign(
    { user: user },
    'secret'
);


// decode when fetching the user from token
const decoded = jwt.verify(req.body.jwtToken, 'secret');
    return res.send({
         user: decoded.user // <-- error here
    });

以下是验证方法的输入:

export declare function verify(
   token: string,
   secretOrPublicKey: string | Buffer,
): object | string;

linter 错误是:

Property user does not exists on typeof "object|string".

我该如何从解码后的 token 中获取数据?

Link to the documentation of the library

最佳答案

使用 Typescript 时,您必须记住输入的所有内容,例如Java 或 C#。 object 是一个父类(super class),不知道属性 user

虽然此代码在 javascript 中有效(您正在查看 javascript 文档),但它在 typescript 中无效。

要修复此错误,请使用 any 转换解码的 token 。

return res.send({
    user: (<any>decoded).user
});

关于node.js - typescript jwt.verify 无法访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50735675/

相关文章:

node.js - 从 firestore 获取数据时使用 async forEach 循环

typescript - 英特尔lij : how to change the syntax of extracted function in typescript?

angularjs - 在加载 AngularJS ap 之前从 AJAX 获取数据

authentication - 如何验证 Kubernetes 服务帐户 token (JWT)

asp.net-core - 如何在 AspNetCore 中仅使用公钥验证使用 x509 签名的 JWT token

jwt - ASP.NET 5 OAuthBearer 身份验证 : The following authentication scheme was not accepted: Bearer

javascript - Node.js 解析路由的最小函数

javascript - 从 Node child_process 执行 Argo Tunnel 时出现错误 1016

node.js - 当我运行 npm start 创建 React 应用程序时缺少脚本

node.js - TypeORM 生成空迁移