我正在尝试用jwt-解码来解码我的令牌,但我做不到,它给了我以下错误。有人知道为什么吗?
错误错误: Uncaught (承诺):TypeError: jwt_decode_1.default不是函数TypeError: jwt_decode_1.default不是RoleGuardService.canActivate上的函数(角色保护服务?d7c4:19)
import jwt_decode from 'jwt-decode';
canActivate(route: ActivatedRouteSnapshot): boolean {
// this will be passed from the route config
// on the data property
const expectedRole = route.data.expectedRole;
const token = localStorage.getItem('token');
// decode the token to get its payload
const tokenPayload = jwt_decode(token);
console.log(tokenPayload);
if (
!this.auth.isAuthenticated() ||
tokenPayload.role !== expectedRole
) {
this.router.navigate(['login']);
return false;
}
return true;
}发布于 2018-02-13 15:26:33
我想你应该像这样进口:
import * as jwt_decode from 'jwt-decode';发布于 2020-10-01 19:41:48
根据文档 +互联网搜索,正确的方法是:
1.安装包+类型
npm install --save jwt-decode
npm install --save @types/jwt-decode
// @ts-忽略来自“jwt-decode”的导入jwt_decode;
否则你会得到这样一个错误

您也可以在tsconfig.json上添加该规则,但只有1次例外:)
发布于 2020-10-15 18:22:52
我也犯了同样的错误,但经过多次尝试,我还是用另一种方法解决了这个问题:
private decode(token: string) {
try {
return JSON.parse(atob(token.split(".")[1]));
} catch (e) {
console.log("error decoding token");
}
}函数atob() 参考文献
https://stackoverflow.com/questions/48770106
复制相似问题