如何在角度9中解码令牌

时间:2020-10-28 10:59:18

标签: angular typescript

我想对令牌进行解码。 但是我会警告。

npm install jwt-decode --save

component.ts:

    import * as jwt_decode from 'jwt-decode';
    .
    .
    .
    console.log("Yes");
    localStorage.setItem('token', res.token);
    this.flagProgressBar = false;
    console.log('res.token: ');
    console.log(res.token);        
    console.log('localStorage token:');
    console.log(localStorage.getItem('token'));
    const tokene = res.token;
    const decoded = jwt_decode(tokene);
    console.log(tokene);
    console.log(decoded);

控制台:

        Yes
        res.token: 
      eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvnQuY29tL3dzLzIwMgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJGdWxsQWRtaW4iLCJleHAiOjE2MDM5MjEzNzMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzU0In0.-e7cYAgQQVTcHlPrw1sWn6IsjhVPfjlItx9XGIn3S9w

localStorage token:    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5WNybNvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJGdWxsQWRtaW4iLCJleHAiOjE2MDM5MjEzNzMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzU0In0.-e7cYAgQQVTcHlPrw1sWn6IsjhVPfjlItx9XGIn3S9w

ERROR TypeError: jwt_decode__WEBPACK_IMPORTED_MODULE_2__ is not a function
at SafeSubscriber.Service.postDataLogin.subscribe.flagProgressBar [as _next]

能否说出我的问题在哪里?

3 个答案:

答案 0 :(得分:3)

对于较新版本(3及更高版本):

jwt_decode导入错误,请尝试import jwt_decode from 'jwt-decode';

答案 1 :(得分:1)

快速的示例应用程序步骤即可完成jwt解码工作:

  1. 安装软件包 https://github.com/auth0/jwt-decode#readme
  2. 导入服务中的依赖项: 从'jwt-decode'导入*作为jwt_decode;
  3. 尝试此示例代码
// Use valid jwt token;
var token = 'eyJ0eXAiO...';
var decoded = jwt_decode(token); 
console.log(decoded);

您报告的错误主要是步骤1和步骤2执行不正确。

答案 2 :(得分:1)

这是针对较旧的版本

import * as jwt_decode from "jwt-decode";

对于较新版本(3及更高版本):

import jwt_decode from 'jwt-decode';