首页 > 解决方案 > 如何在 reactJS + axios + nodeJS 中呈现 API 错误响应?

问题描述

我需要呈现我的 API 给我的错误,比如res.status(422).json({ error: error.message }),它给我带来的信息是密码验证。我尝试使用一些 axios 工具,但没有任何效果,比如 .catch。你能帮助我吗?

反应:

function Register() {
  const [email, setEmail] = useState(``);
  const [name, setName] = useState(``);
  const [password, setPassword] = useState(``);

  async function onSubmit(event) {
    event.preventDefault();

    async function handleSubmit() {
      const response = await axios.post("http://localhost:3001/usuario/register",{
          email,
          name,
          password,
        },{
          headers: { "Content-Type": "application/json" },
        }
        
      );
      console.log(response.data);
      const { data } = response;
      return data
    }
    await handleSubmit();
  }

  return (
    <div>
       ...
    </div>
  )
}

节点JS:

async adicionaRegistro(infosReg, res) {
    
    const dataCriacao = moment().format("YYYY-MM-DD h:mm:ss");
    const status = 1;
    
    const name = infosReg.name;
    const email = infosReg.email;
    const password = infosReg.password;

    try {
      const usuario = new Usuario({
        name,
        email,
        dataCriacao,
        status
      });

      res.status(201).json();
    } catch (erro) {
      if (erro instanceof InvalidArgumentError) {
        console.log(erro)
        res.status(422).json({ erro: erro.message });
      } else if (erro instanceof InternalServerError) {
        res.status(500).json({ erro: erro.message });
      } else {
        res.status(500).json({ erro: erro.message });
      }
    }
  }

标签: node.jsreactjsapihttpaxios

解决方案


如何try...catch捕捉错误?https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

function Register() {
  const [email, setEmail] = useState(``);
  const [name, setName] = useState(``);
  const [password, setPassword] = useState(``);

  async function onSubmit(event) {
    event.preventDefault();

    async function handleSubmit() {
      let response;
      try {
        response = await axios.post(
          "http://localhost:3001/usuario/register",
          {
            email,
            name,
            password,
          },
          {
            headers: { "Content-Type": "application/json" },
          }
        );
      } catch (e) {
        console.log(e);
        // here you will see the result if your backend is throwing an error
      }
      if (response) {
        console.log(response.data);
        const { data } = response;
        return data;
      }
    }
    await handleSubmit();
  }

  return <div>...</div>;
}

推荐阅读