JWT令牌存储与获取异常求助:浏览器端返回undefined
JWT令牌获取用户邮箱异常排查与解决
问题现象
- 无法从请求头获取token,JWT令牌未正确传递至后端
- localStorage无用户信息,前端代码执行返回
undefined - 请求头Cookie格式存在编码异常
- Thunder Client测试接口正常,但浏览器端调用返回
undefined
后端存储Cookie代码
router.post('/signin',async(req,res)=>{ // 待补充更多验证逻辑:用户存在性、密码正确性等 console.log("reached signin page successfully"); const email = req.body.email; const password = req.body.password; const users = await User.findOne({ email }) if(users) { console.log("successfully logged in") const passcompare = password === users.password; if(passcompare) { const token = jwt.sign(email, JWT) res.status(200); res.cookie("cookie", token, { httpOnly:true // secure:process.env.NOD_ENV==="production", // maxAge:1000, // signed:true, }) res.json({ success:true, token }); } else { res.json({ success:false, msg: "password incorrect" }) } } else { res.json({ success:false, msg:"No user found With the above credentials" }) } }) // 受中间件保护的接口 router.get('/signinn',fetchuser,async (req,res)=>{ console.log("reached signnn"); let userdata = await User.findOne({ email:req.email }) if(userdata) { res.json({ userdata }) } }) // 身份验证中间件 const fetchuser = async (req,res,next)=>{ console.log("reached middleware") const token2 = req.headers.token; // const token2 = req.cookies.cookie; // console.log(token2) if(!token2) { res.status(401).send({ msg:"No token found" }) } else { try { const data = jwt.verify(token2,JWT); req.email = data; next(); } catch(error) { res.status(401).send({ msg:"No token found" }) } } }
前端获取数据代码
const [username,setusername] = useState() useEffect(()=>{ fetch('http://localhost:4000/user/signinn') .then((response)=>response.json()) .then((data)=>setusername(data)) },[]) console.log("hello",username);
请求头中的Cookie信息
cookie=eyJh%---some more text ------% dRNc3d4Y7o; Path=/; HttpOnly
问题根源与解决步骤
1. 后端中间件未正确读取Cookie
当前中间件从req.headers.token取令牌,但实际令牌存在Cookie中(且HttpOnly属性禁止前端操作),需修改中间件读取Cookie:
const fetchuser = async (req,res,next)=>{ console.log("reached middleware") // 改为读取Cookie中的令牌 const token2 = req.cookies.cookie; console.log(token2) if(!token2) { res.status(401).send({ msg:"No token found" }) } else { try { const data = jwt.verify(token2,JWT); req.email = data; next(); } catch(error) { res.status(401).send({ msg:"Invalid token" }) } } }
2. 前端Fetch请求未携带Cookie
浏览器跨域请求默认不携带Cookie,需在Fetch中添加凭证配置:
useEffect(()=>{ fetch('http://localhost:4000/user/signinn', { credentials: 'include' // 强制携带Cookie }) .then((response)=>{ if(!response.ok) throw new Error('请求失败'); return response.json() }) .then((data)=>setusername(data)) .catch(err=>console.error(err)) },[])
3. 后端配置跨域允许携带凭证
若前后端端口/域名不同,需在后端CORS配置中开启凭证支持:
const cors = require('cors'); // 替换为你的前端实际域名 app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
4. JWT签名格式优化
当前直接传入字符串签名,建议改为对象格式便于后续扩展:
// 签名时 const token = jwt.sign({ email: email }, JWT); // 验证时 const data = jwt.verify(token2,JWT); req.email = data.email;
内容的提问来源于stack exchange,提问作者codingsolution
相关产品推荐
相关产品推荐

