[英]Invalid Token Error: Invalid token specified: Cannot read property 'replace' of undefined?
I was trying to decode token created through jwt, so that I can access values in my react page and and use it.But for some reason it shows "InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined" this error, I really need help on this, thankyou very much in advance to whoever answers this.我试图解码通过 jwt 创建的令牌,以便我可以访问我的反应页面中的值并使用它。但由于某种原因它显示“InvalidTokenError:指定的无效令牌:无法读取未定义的属性'替换'”这个错误,我真的需要这方面的帮助,非常感谢任何回答这个问题的人。
Front-End in react.js,decoding the token react.js 中的前端,解码令牌
useEffect(()=>{ const token=localStorage.usertoken const decoded = jwt_decode(token); setinfo({ id:decoded._id, email:decoded.email, username:decoded.username, }) },[])
Back-end node.js后端 node.js
router.get("/info",authenticateToken,(req,res)=>{ UserProfile.findOne({_id: req.user._id}).then(user=>{ console.log(user); if(user){ res.json(user) } else { res.send("User does not exist") } }).catch(err=>{ res.send("error:"+err); }) }) function authenticateToken(req,res,next){ const authHeader= req.headers['authorization'] const token = authHeader && authHeader.split(' ') if(token == null) return res.sendStatus(401) jwt.verify(token,secretkey,(err,user)=>{ if(err) return res.sendStatus(403) req.user = user next(); }) }
I think the way you are accessing the token from localStorage is wrong.我认为您从 localStorage 访问令牌的方式是错误的。 Instead of
代替
localStorage.usertoken
use利用
localStorage.getItem("userToken")
considering you have set user token by考虑到您已通过以下方式设置用户令牌
localStorage.setItem("userToken", token_received_from_backend);
I found this article that worked for me:我发现这篇文章对我有用:
https://www.onooks.com/invalid-token-specified-cannot-read-property-replace-of-undefined/ https://www.onooks.com/invalid-token-specified-cannot-read-property-replace-of-undefined/
In summery it suggest that you clear your browser's local storage cache using the developer tools "F12" and go to Storage\Local Storage, right click and clear.总结一下,建议你使用开发者工具“F12”和go清除浏览器的本地存储缓存到Storage\Local Storage,右键清除。
I also got the same error.我也遇到了同样的错误。 In my case, I have got one mistake.
就我而言,我犯了一个错误。 In Localstorage please remove the token variable and refresh the page
在 Localstorage 中请移除 token 变量并刷新页面
When you call the cloud function, Try to add the full function url in the post request instead of "/login".当您调用云function时,请尝试在post请求中添加完整的function url而不是“/ login”。
for me i tryed remove useState() and change with veriable exemple:对我来说,我尝试删除 useState() 并使用可验证的示例进行更改:
// const [user , setUser] = useState({}); # Remove This <
let user; // Use This
// cooking-login jwt
const jwtlogin = (mytoken) => {
// Decode JWT token
const decoded = jwtDecode(mytoken)
// set emails State
user = decoded;
// set cookie
cookies.set("jwt_auth",mytoken, {
expires: new Date(decoded.exp * 1000),
})
}
Just This and Thanks只有这个,谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.