前言
在如今得环境下,越来越多得项目采用微服务,前后端分离项目。优点在于同时开发,分开部署。缺点在于需要约定的太多,导致前后端联调产生分歧。就标题而言,解决前端antd 接收后台返回的jwt token字符串 进行解析做记录。
关于jwt
三部分组成(其他的不做过多介绍,又不是本文的主题 ha ha ha ~~~)
第一部分我们称它为头部(header),第二部分我们称其为载荷(payload, 类似于飞机上承载的物品),第三部分是签证(signature).
例如:
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ8.eyJhdWQiOlsic2VydmljZS1hcnRpY2xlIiwic2VydmljZS1hdXRoIl0sImZ1bmN0aW9uTGlzdCI6ImhhaCIsInVzZXJfbmFtZSI6IjEzMDY2NzY2MTkzIiwic2NvcGUiOlsiYWxsIl0sIm5hbWUiOiLlvKDkuInkuLAiLCJleHAiOjE2MDUyNDM1MjUsImF3dGhvcml0aWVzIjpbImJhc2ljLmFkZCJdLCJqdGkiOiIzZjI0NzI1NC0zMzVhLTQ5MGItOTEyZC1jYTBhYWRkZmVkOTMiLCJjbGllbnRfaWQiOiJwYyJ9.xTKDzfxwGZVwIMf3nm4C8f0bfoEKy1AVqDO1LNGDjz9z4UCRJmSyTXAYAx3Ph_GHLKIa3IGpMoVz1aAwKwZ2GqpFI1uKwReK4Nl8K92pHUwNNFxkbhPcOauWjsrw5BDHn3jBOC2GhUTrY0kifaJ4FjAAIbyVGr04VhZMp6sYdfrWUVLHm3d848RR3JW_OvMJfWOnuRJ-T1SMho9buLmSKUtBexWXb-uQY72BicGRJIrSJk4QlGHYzb4jss39DFU_bszLXJXoM4ho8n-qmUdjy0gmhr-csIbctSCEVZeTyKO_KJ9HrU6UgnIjErj-fCJVXElXaddkZpjpthTQf-I8iA
解析
let tokenString = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ8.eyJhdWQiOlsic2VydmljZS1hcnRpY2xlIiwic2VydmljZS1hdXRoIl0sImZ1bmN0aW9uTGlzdCI6ImhhaCIsInVzZXJfbmFtZSI6IjEzMDY2NzY2MTkzIiwic2NvcGUiOlsiYWxsIl0sIm5hbWUiOiLlvKDkuInkuLAiLCJleHAiOjE2MDUyNDM1MjUsImF3dGhvcml0aWVzIjpbImJhc2ljLmFkZCJdLCJqdGkiOiIzZjI0NzI1NC0zMzVhLTQ5MGItOTEyZC1jYTBhYWRkZmVkOTMiLCJjbGllbnRfaWQiOiJwYyJ9.xTKDzfxwGZVwIMf3nm4C8f0bfoEKy1AVqDO1LNGDjz9z4UCRJmSyTXAYAx3Ph_GHLKIa3IGpMoVz1aAwKwZ2GqpFI1uKwReK4Nl8K92pHUwNNFxkbhPcOauWjsrw5BDHn3jBOC2GhUTrY0kifaJ4FjAAIbyVGr04VhZMp6sYdfrWUVLHm3d848RR3JW_OvMJfWOnuRJ-T1SMho9buLmSKUtBexWXb-uQY72BicGRJIrSJk4QlGHYzb4jss39DFU_bszLXJXoM4ho8n-qmUdjy0gmhr-csIbctSCEVZeTyKO_KJ9HrU6UgnIjErj-fCJVXElXaddkZpjpthTQf-I8iA';
let user = JSON.parse(decodeURIComponent(escape(window.atob(tokenString.split('.')[1]))))
console.log("user", user)
结果:
新方法:
1.安装jwt模块
npm install jsonwebtoken
2.在js文件中引用
var jwt = require(“jsonwebtoken”);
3.解码
jwt.decode(‘token’)
总结
该解析其实不是react专用写法,本身是一个js写法,只不过适用于react,在于平常积累。如有问题请指导,勿喷,感激不尽。