How do I show the error message sent by Express?

Asked

Viewed 658 times

-1

I have the following method in back-end, who logs in:

const login = async (req, resp) => {
  try {
    if (!req.body.id) throw 'Necessário Informar ID';

    const ongFromDB = await db('ongs').select('name').where({ id: req.body.id }).first();

    if (!ongFromDB) throw 'ONG não Encontrada.';

    resp.status(201).send(ongFromDB);
  } catch (error) {
    resp.status(400).send(error);
  }
};

And I’m trying to get front-end with React:

function handleLogon(e) {
  e.preventDefault();
  api.post('/login', { id })
    .then(response => {
      localStorage.setItem('ongId', response.data.name);
      console.log(response.data.name);
      history.push('/profile');
    })
    .catch(e => {
      alert(e.data); // Ou alert(e)
    });
}

But I can’t get the text, even if Postman can see the message.

I can only get something like:

Error: Request failed with status code 400

1 answer

0

When Axios makes a request that finds a status error - 4xx or 5xx -, an error will be thrown. This error will be captured by the method catch, of his Promise.

This error will contain an object response, which you can use for response properties. See documentation of that library to learn more.

Utilize error.response.data to get the text you are sending from back-end:

api
  .post('/login', {})
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error.response.data);
  });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.