我的checkAuth鉴权函数始终返回true,是什么原因导致的?
问题根因&修复方案
1. 最核心的错误:异步函数调用逻辑错误
checkAuth是async异步函数,不管内部返回什么值,外层拿到的永远是Promise对象,而Promise对象本身是真值,你直接写if(!checkAuth())时,!Promise的结果永远是false,所以永远不会触发重定向逻辑,看起来就像checkAuth始终返回true。
2. 服务端参数解析错误
你服务端接收参数的写法错误,前端传的是{email: 具体值}的结构,所以需要解构才能拿到正确的email值:
// 修复后的服务端checkToken代码 const checkToken = asyncHandler(async (req, res) => { const { email } = req.body; // 这里要解构,不能直接赋值req.body const user = await User.findOne({ email }) // findOne要传查询条件对象,属于规范写法 if (user) { res.json({ token: user.token, }); } else { res.status(400) throw new Error("Niet ingelogd.") } });
3. 前端LandingPage逻辑修复
需要修改useEffect内的异步调用逻辑、加上跳转的return语句:
// 修复后的LandingPage.js import React from "react" import { useEffect, useState } from "react" import { Redirect } from "react-router-dom" import checkAuth from "./CheckAuth.js" export default function LandingPage() { const [redirect, setRedirect] = useState(false); useEffect(() => { // 内部封装异步执行逻辑 const verifyAuth = async () => { const authResult = await checkAuth(); if (!authResult) { setRedirect(true); console.log("false"); } } verifyAuth(); }, []) if (redirect) { return <Redirect to="/"/> // 这里必须return跳转组件才会生效 } return ( <div> <h1>whatsup</h1> </div> ) }
4. 可选优化:给CheckAuth加空值判断
避免localStorage没有userInfo时JSON.parse直接报错:
// 优化后的CheckAuth.js import axios from "axios" const checkAuth = async () => { try { const userInfo = localStorage.getItem("userInfo"); if (!userInfo) return false; // 本地没有登录信息直接返回未授权 const info = JSON.parse(userInfo); const email = info.email; const origintoken = info.token; const config = { headers: { "Content-type": "application/json" } } const { data } = await axios.post ( "/api/users/token", {email}, config ); return origintoken === data.token; } catch (error) { console.log("error", error); return false; } } export default checkAuth
内容的提问来源于stack exchange,提问作者MultiThunderXXL
相关产品推荐
相关产品推荐

