<react+jsonwebtoken 踩坑>无法将 jsonwebtoken 与最新版本的 react 一起使用

588 阅读1分钟

版本

采用create-react-app创建的

"jsonwebtoken": "^8.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",

问题

想要用jsonwebtoken 将后端传过来的jwt字符串转化为对象,但是引入时报错,显示

ERROR in ./node_modules/buffer-equal-constant-time/index.js 4:13-37

Module not found: Error: Can't resolve 'buffer' in 'C:\Users\missingone6\Desktop\WeShare\we-share\weshare\node_modules\buffer-equal-constant-time' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }' - install 'buffer' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "buffer": false }

ERROR in ./node_modules/jwa/index.js 3:13-30

Module not found: Error: Can't resolve 'crypto' in 'C:\Users\missingone6\Desktop\WeShare\we-share\weshare\node_modules\jwa' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }

解决

jsonwebtokens是node的 JWT 库,而不是浏览器中的 JWT 库。

最新的版本react不支持这个库。并且在前端使用引入jsonwebtoken 将后端传过来的jwt字符串转化为对象,有点小题大做了。改用js原生的atob方法。

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjY2NiIsImlhdCI6MTY3NDc1MDE3OSwiZXhwIjoxNjc0NzUwMTgwfQ.2pLsqyiLR8J4Oq0KSK2aeVdjgFAeVHLe2kg_wEyYyP0';
console.log(JSON.parse(window.atob(token.split(".")[1])));

image.png