如何显示来自 express 后端的错误消息以响应前端?

How to display error message from express backend to react frontend?

我正在创建一个 MERN 应用程序并设置一个错误处理程序函数,该函数在不满足某些条件时显示错误消息。就我而言,我有一个注册页面,要求电子邮件有效并且密码至少为 6 个字符。现在,这些消息在我的 VS Code 后端控制台上准确显示,但我无法在浏览器 s/frontend 的控制台上显示它们。我查看了 this SO post 但仍然无法解决我的问题。我怀疑这是因为我的前端和后端在不同的端口上,但我仍然不知道如何修复它。代码在下面 posted。

路线代码

const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { email: '', password: ''};


    //duplicate error code
    if(err.code === 11000){
        errors.email = "that email is already registered";
    }

    //Just a way to create custom error messages
    if(err.message.includes("Creator validation failed")){
        Object.values(err.errors).forEach(({properties}) => {
            errors[properties.path] = properties.message;
        });
    }

    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'efrgvwrtgr435f345secret', {
        expiresIn: maxAge
    });
}

router.route('/add').post((req,res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const bio = req.body.bio;
    const creatorName = req.body.creatorName;
    const password = req.body.password;
    const email = req.body.email;

    const newCreator = new Creator({firstName, lastName, bio, creatorName, password, email})

        newCreator.save()
        .then(() => { 
            const token = createToken(newCreator._id);
            res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000}).json("Token is " + token);
            // res.json("New creator added!");
            res.send("New creator added!");
            
        })
        // .catch((err) => { const errors = handleErrors(err); res.status(404).json({ errors })});
        .catch((err) => { const errors = handleErrors(err); res.status(404).send({ errors })});
})

从注册页面提交操作代码

const handleSubmit = (e) => {
        e.preventDefault()

        const creator = {
            firstName: firstName,
            lastName: lastName,
            creatorName: creatorName,
            bio: bio,
            creatorName: creatorName,
            password: password,
            email: email
        }

        console.log(creator);
        
//If there are any errors when the submit btn was clicked, I want those errors to be displayed on the browser's console
        try {
            axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
            // .then((res) => console.log(res.data))
            .then((res) => console.log(res.json));
            history.push('/marketplace');
        }
        
        catch (err) {
            console.log(err);
        }
    }

当您使用 res.status(404).send({ errors }) 发送响应时,您可以告诉客户端错误代码 - Axios 有办法捕获所有不在 200 (OK) 范围内的代码。本质上,如果错误代码与响应一起发送,您可以使用 error.response.data:

查看错误数据
axios.post('http://localhost:5000/creators/add', creator, {withCredentials:true}) //Goes to the server('http://localhost:5000/creators/add')
    .then((res) => console.log(res.json))
    .catch((error) => {
        if(error.response) console.log(error.response.data);
    })

来源:https://axios-http.com/docs/handling_errors