【问题标题】:How to display errors with Axios in React如何在 React 中使用 Axios 显示错误
【发布时间】:2020-11-28 22:00:59
【问题描述】:

早安,

我在使用 Axios 时遇到了一个小问题,我想检查状态代码是否正常,如果不是,我将错误发送给客户端。我该怎么做?

这是我的尝试,但没有成功:

路线代码:

router.post("/register", async (req, res) => {
    try {
        //check if fields are empty
        const { name, email, password, rePassword } = req.body;
        if (!name || !email || !password || !rePassword) {
            return res.status(406).send("fields are empty");
        }

        //passsword length should be at leats 6 characters
        if (password.length < 6) {
            return res
                .status(406)
                .send("Password should at least be 6 characters long");
        }
        //checking if passwords match
        if (password !== rePassword) {
            return res.status(406).send("Passwords dont match");
        }
        //check if user exists
        const emailExist = await User.findOne({ email: req.body.email });
        if (emailExist) {
            return res.status(406).send("User already exists");
        } else {
            //create salt
            const salt = await genSalt(10);
            //hashing the password
            const hashedPassword = await hash(req.body.password, salt);
            const user = new User({
                name: req.body.name,
                email: req.body.email,
                password: hashedPassword,
                isAdmin: req.body.isAdmin,
            });
            const newUser = await user.save();
            res.status(200).send(newUser);
        }
    } catch (err) {
        console.log(err);
    }
});

页面代码:

const handleSubmit = async e => {
        e.preventDefault();
        axios
            .post("http://localhost:5000/users/register", {
                name,
                email,
                password,
                rePassword,
            })
            .then(response => {
                console.log(response.data);
            })

            .catch(err => {
                console.log(err);
            });
}

【问题讨论】:

    标签: node.js api express axios


    【解决方案1】:

    响应将为您提供以下选项

    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
    

    这将允许您检查有效的状态文本/代码,或相应地显示错误。

    【讨论】:

    • 它只显示:xhr.js:177 POST localhost:5000/users/register 406(不可接受)错误:请求失败,状态码 406 在 createError (createError.js:16) at set (settle.js :17) 在 XMLHttpRequest.handleLoad (xhr.js:62)
    猜你喜欢
    • 2022-12-05
    • 2020-04-15
    • 2021-06-10
    • 2017-11-07
    • 2022-01-17
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多