【问题标题】:How do I get reponse data from 400 http response in ReactJS如何从 React JS 中的 400 http 响应中获取响应数据
【发布时间】:2020-06-10 13:00:51
【问题描述】:

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

 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);
    }

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    你需要一个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);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 2017-12-28
      • 2020-04-18
      • 2022-06-28
      • 2011-04-12
      • 2020-06-05
      • 1970-01-01
      相关资源
      最近更新 更多