【问题标题】:Right-hand side of 'instanceof' is not an object, jsonwebtoken\'instanceof\' 的右侧不是对象,jsonwebtoken
【发布时间】:2023-01-31 13:59:13
【问题描述】:

我将在我的 React 项目中使用 jsonwebtoken 创建表单数据标记。

import jwt from 'jsonwebtoken';

const MyForm = () => {
    const submitForm = (e) => {
       e.preventDefault();
       const data = { name: 'name', email: 'email', subject: 'subject', message: 'message' };
       const token = jwt.sign(data, 'qwerty');
       console.log(token);
    }
    return(
        <form onSubmit={submitForm}>
            ...
        </form>
    );
}
export default MyForm;

发生以下错误。

TypeError: Right-hand side of 'instanceof' is not an object
push../node_modules/jsonwebtoken/sign.js.module.exports [as sign]
../node_modules/jsonwebtoken/sign.js:108
  105 |   return failure(new Error('secretOrPrivateKey must have a value'));
  106 | }
  107 | 
> 108 | if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {
      | ^  109 |   try {
  110 |     secretOrPrivateKey = createPrivateKey(secretOrPrivateKey)
  111 |   } catch (_) {
View compiled
submitEmail
../MyForm.js:22
  19 |    e.preventDefault();
  20 |    
  21 |    const data = { name: 'name', email: 'email', subject: 'subject', message: 'message' };
> 22 |    const token = jwt.sign(data, 'qwerty');
     | ^  23 |    console.log(token)
  24 | 
  25 | 

为什么这会给我那个错误? 我试图解决这个问题,但还没有结果。
并感谢任何修复它的帮助。谢谢。

【问题讨论】:

  • 只需转到您正在使用的 jsonwebtoken 包的 npm 页面,打开它的 github 存储库,打开问题选项卡并查找 'instanceof' is not an object。你会发现唯一的 1 issue 声明 jsonwebtoken is a Node.js module, its use in a browser was never intended. Versions before 9.0.0 could use webpack's polyfill of the Node.js built-in modules. 和一些额外的细节。
  • 您使用的是什么版本的 Node 和 jsonwebtoken 模块?

标签: javascript reactjs jwt


【解决方案1】:

我遇到过同样的问题。问题是jsonwebtoken包的9.0.0版本不支持节点11及以下版本,所以我通过降级jsonwebtoken包的版本解决了这个问题。

我通过更改 jsonwebtoken 依赖项来做到这一点从 9.0.0 到 8.5.1在 package.json 文件中,然后我跑了npm 更新在我的终端内。

此处可能建议升级您的节点版本,但由于 npm 问题,我还没有完全更新我的节点版本,因此这只是一种解决方法。

查看以下文章,解释 jsonwebtoken 包从 v8 到 v9 的迁移。 https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v8-to-v9

【讨论】:

  • 但是版本<9.0.0是一个安全问题,所以我们必须更新到9.0.0的jsonwebtoken
【解决方案2】:

jsonwebtoken 是一个节点模块。换句话说,它不能很好地在浏览器上运行。看到这个 issue here. This page 为客户端 jwt 操作提供了很好的替代方案。

【讨论】:

    【解决方案3】:

    在这种情况下,你需要使用最新的节点版本,所以请先检查你的节点版本这个错误可以在版本10.*.*

    所以更新你的 Nodejs 版本

    【讨论】:

      【解决方案4】:

      在最新的 jsonwebtoken,v9 中: 可能想尝试...

      let secret = 'qwerty';
      const token = jwt.sign(data, secret.toString('utf-8'));
      

      此外,您可能需要添加参数以强制执行旧行为...

      const token = jwt.sign(data, secret.toString('utf-8'), { algorithm: 'HS256', allowInsecureKeySizes: true, allowInvalidAsymmetricKeyTypes: true });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-11
        • 2023-02-14
        • 2019-11-16
        • 2017-09-16
        • 2017-01-18
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        相关资源
        最近更新 更多