首页 > 解决方案 > 在 Angular 中使用 jsonwebtoken 会导致 Uncaught ReferenceError: global is not defined

问题描述

我想使用 jsonwebtoken npm 的jwt.sign(payload, secretOrPrivateKey, [options, callback])方法,但我不断收到错误

Uncaught ReferenceError: global is not defined
at Object../node_modules/buffer/index.js (index.js:43)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/safe-buffer/index.js (index.js:2)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/jws/lib/sign-stream.js (sign-stream.js:2)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/jws/index.js (index.js:2)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/jsonwebtoken/decode.js (decode.js:1)
at __webpack_require__ (bootstrap:78)

我读了很多关于这个问题的内容,添加了这个:

polyfills.ts
(window as any).global = window;

抛出新错误

psSupported.js:3 Uncaught ReferenceError: process is not defined
at Object../node_modules/jsonwebtoken/lib/psSupported.js (psSupported.js:3)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/jsonwebtoken/verify.js (verify.js:6)
at __webpack_require__ (bootstrap:78)
at Object../node_modules/jsonwebtoken/index.js (index.js:3)
at __webpack_require__ (bootstrap:78)
at Module../src/app/app.component.ts (main.js:95)
at __webpack_require__ (bootstrap:78)
at Module../src/app/app.module.ts (app.component.ts:11)
at __webpack_require__ (bootstrap:78)

(我看到了几个例子,例如 express-jsonwebtoken 但它们是纯 js 我没有太多经验将完整的 js 库添加到 Angular 项目。)

有没有办法解决这个问题或有任何替代方法使用 jsonwebtoken like sign method from another lib under Angular 8.0 ?

标签: angularjwt

解决方案


最后我可以在 Angular 8 中使用 jsonwebtoken。

这是我所做的,我不确定他们做了什么,但我想帮助其他人让他们更接近一点,如果他们得到持续的错误。

此列表的灵感来自控制台上有关流、加密、全局、缓冲区、进程等的错误。

安装

    crypto-js
    stream

将一些额外的行写入默认 js 文件:

    browser.js
    node:  { crypto: true, stream: true },

    polyfills.js
    import { global } from '@angular/compiler/src/util';

    (window as any).global = window;
    global.Buffer = global.Buffer || require('buffer').Buffer;
    (window as any).process = {
        env: { DEBUG: undefined },
    };

配置:

    tsconfig.app.json
      "paths": {
        "stream": ["../node_modules/stream-browserify/index.js"],
        "crypto": ["../node_modules/crypto-js"]
      }

    tsconfig.json
        "paths": {
          "stream": ["../node_modules/stream-browserify/index.js"],
          "crypto": ["../node_modules/crypto-js"
          ]
      }

总而言之,它现在有效。

乔巴


推荐阅读