在 angular-cli 应用程序中使用 jsonwebtoken 时出错

Error using jsonwebtoken with angular-cli application

我有一个 angular2 应用程序,它在我的 angular2 应用程序上使用 angular-cli for the scaffold and other tasks, but now I can't use jsonwebtoken

我添加了依赖

yarn add --save jsonwebtoken

我实际上可以在 node_modules 看到图书馆,我做了

import { jwt } from 'jsonwebtoken'

在我的 TypeScript 代码中 IDE 没有给我警告,所以它可以正确找到依赖项。

但是当我执行 npm startyarn start 时,我收到以下错误消息

ERROR in ./~/isemail/lib/index.js
Module not found: Error: Can't resolve 'dns' in '/home/$MY_USER_NAME_PLACE_HOLDER/dir/to/my/app/node_modules/isemail/lib'
 @ ./~/isemail/lib/index.js 5:12-26
 @ ./~/joi/lib/string.js
 @ ./~/joi/lib/index.js
 @ ./~/jsonwebtoken/sign.js
 @ ./~/jsonwebtoken/index.js
 @ ./src/app/_auth/authentication.service.ts
 @ ./src/app/app.component.ts
 @ ./src/app/index.ts
 @ ./src/main.ts
 @ multi main

ERROR in [default] /home/$MY_USER_NAME_PLACE_HOLDER/dir/to/my/appsrc/app/_auth/authentication.service.ts:41:24 
Property 'validate' does not exist on type 'typeof "/home/$MY_USER_NAME_PLACE_HOLDER/dir/to/my/app/node_modules/@types/jsonwebtoken/index"'.

当我在互联网上搜索错误时,我关注了一系列对话和相关项目。 我发现:

但我的问题是,angular-cli 有 no way to override webpack config 并且无意更改它。

所以我不知道在这里做什么,你知道如何在我的 angular-cli 应用程序中使用 jsonwebtoken 吗?

我 运行 在尝试使用 jsonwebtoken client-side 时遇到了同样的问题(jsonwebtoken 在我的 Express 应用程序中工作得很好 server-side)。

简短的回答是,可能无法在您的 angular 应用程序中使用 https://github.com/Hendrixer/jwt-decode jsonwebtoke。如果您只想解码 JWT 的 client-side 来执行验证之类的事情,那么该库有点重,并且该模块实际上是供 server-side 在 node.js 中使用。

但是,在 angular 2(包括 angular-cli、webpack 中)中,有许多可用的替代方案可以在客户端工作。例如,Jwt-decode 将解码 JWT。

但是,我发现最好的替代方法是重构我的代码以使用 Angular2-JWT 的 AuthHttp class,它负责为您传递 http header 中的令牌.如果令牌不存在或未通过验证,它也会抛出错误,您可以随意处理。