javascript 我在MERN中与post API连接错误,api在后端提供正确的输出,但在前端反向

46qrfjad  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(91)

嗨,我正在学习MERN,并试图解决有关登录页面的API连接问题。**handeLoginSubmit()**在提交登录表单时运行,并尝试N catch。
输入错误的凭据或仅正确的凭据,try块从后端运行,它给出错误,但在前端,它在正确/错误的凭据上显示成功

>front-end(react code)

async function handeLoginSubmit(e) {
        e.preventDefault();
        try {
            await axios.post('/login', { email, password });
            alert('Login Successfull')
            // console.log('No - error');
        } catch (e) {
            // console.log('error');
            alert('Login Failed!')
        }
    }

----------------------------------------------

> backend code for express server with post request 

app.post('/login', async (req, res) => {
    const { email, password } = req.body;
    const userDoc = await User.findOne({ email });
    console.log(userDoc);
    if (userDoc) {
        const passOk = bcrypt.compareSync(password, userDoc.password)
        if (passOk) {
            res.json('passok')
        } else {
            res.status(422).json('wrong crediantials')
        }
        console.log(' user found');
    } else {
        res.json('not found!!')
        console.log('not found!!')
    }
})
2w3kk1z5

2w3kk1z51#

将axios请求存储在变量中,并在条件中检查变量auth,并显示来自后端的数据

>For frontend

async function handeLoginSubmit(e) {
        e.preventDefault();
        try {
            const auth = await axios.post('/login', { email, password });
            console.log(auth);
            if (auth) {
                alert(auth.data)
            } else {
            }
            // console.log('No - error');
        } catch (e) {
        }
    }

--------------------------------------------
>For backend

app.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;
        const userDoc = await User.findOne({ email });
        console.log(userDoc);
        if (userDoc) {
            const passOk = bcrypt.compareSync(password, userDoc.password)
            if (passOk) {
                res.json('passok')
            } else {
                res.status(422).json('wrong crediantials')
            }
            console.log(' user found');
        } else {
            res.json('not found!!')
            console.log('not found!!')
        }
    } catch (error) {

    }
}
)

相关问题