How to return JSON resulting from POST to the front end and display the data?

Asked

Viewed 21 times

0

Although with some years of programming experience, I’m still beginner in web/mobile development. Please, patience...

I researched and tried some treatments but without success, for something that seems to me quite simple.

Goal: Return to the front end the result of the POST request executed in the back end, treat and redirect the returned information.

What I am wearing: No back-end knex usage persisting in Sqlite. No front-end React with typescript.

I am trying as follows in the back-end (synthesized code):

try {
  await trx('agendamento').insert({
                usuario_agend, data_agend, hora_agend
  });
  await trx.commit();
  return res.status(201).json(res);  // <== AQUI tento retornar o json
} catch(err) {
  await trx.rollback();
  return res.status(400).json({
    error: 'Erro inexperado ao inserir novo agendamento: ' + err
  });
};    

As can be seen, in case of success in the POST, I try to return the status and json by the instruction "Return res.status(201). json(res);". I had researched and understood that this 'res' would contain the result of "commit", however, analyzing the contents of the 'res' does not seem well.

Also, I couldn’t handle a returned json on the front end. My front-end looks like this (synthesized code):

api.post('agendamentos', {
  usuario_agend, 
  data_agend,
  hora_agend
}).then(() => {      
  //alert('Agendamento realizado com sucesso!');      
  history.push({
    pathname: '/sucessoagendamento',
    state: { detail: response.data }
  })
}).catch((error) => { 
  if (error.response){
    alert('Erro ao tentar realizar agendamento: ResponseError = ' + error.response);
  }
});

I want to replace simple commented 'Alert', I tried using 'history.push' but 'Response.data' presents me as not being valid.

So I’d like to know:

1. Which correct way to return the result of the POST method in a json to the front end in the back end?

2. How to capture the received json on the front end and redirect to a new confirmation form of the persisted data?

Could you please help me with this. All help is welcome.

Thank you.

No answers

Browser other questions tagged

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