首页 > 解决方案 > 如何从 ReactJS 中的 400 http 响应中获取响应数据

问题描述

我已经在后端设置了快递,如果帐户已经存在,这就是逻辑。

 try {
        //check if email already exists
        const existingUser = await User.findOne({ email : email });
        if (existingUser) {
            // return res.send('Already exists')
            return res.status(400).json({err: "Account with email already exists"});
        };

我能够使用 axios 为 200/201... 响应获取数据。但不是为了这个。IT 还将 json 响应返回给 POSTMAN,但不返回 400 代码的 axios。我需要提取 我的前端代码的响应数据!

   const submit = async (e) => {
        e.preventDefault();
        if(password !== password2){
            setErr("Passwords do not match")
        };
        const userData = { name, email, password };
        const url = "http://localhost:5000/api/users/signup";
        const res = await axios.post(url, userData);
        // NO OUTPUT
        console.log(res.data);
        console.log(res);
    }

标签: javascriptnode.jsreactjsexpressaxios

解决方案


你需要一个try / catch

  const submit = async e => {
    e.preventDefault();
    if (password !== password2) {
      setErr("Passwords do not match");
    }
    const userData = { name, email, password };
    const url = "http://localhost:5000/api/users/signup";
    try {
      const res = await axios.post(url, userData);
    } catch (err) {
      console.log(err.response);
    }
  };

推荐阅读