Is there any difference between these two post methods [ Typescript ]?

Viewed 47

Hi I am trying to send a request with fetch method. Normally I will use axios to send request. Now i am trying something new in typescript.

Here is the axios version of the request. Its working fine. The email got sent

axios
  .post('http://localhost:3000/login/email', { email: emailToBeSent })
  .then(res => {
    alert(emailToBeSent);
  })
  .catch(err => {
    alert(emailToBeSent + 'error not sent');
  });

But when i try with the fetch, mail won't be sent but response return success but its indicating bad request

const data = { email: emailToBeSent };
    fetch('http://localhost:3000/login/email', {
      method: 'POST', // or 'PUT'
      body: JSON.stringify(data),
    })
      .then(response => {
        console.log('Success:', response);
      })
      .catch(error => {
        alert('Error:');
      });

Can anyone suggest what I am missing here?

Here is the response

enter image description here

1 Answers

Most likely server rejects the request because content type is not specified (axios does it for you by default). Add a Content-Type header:

fetch('http://localhost:3000/login/email', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data),
})

Regarding the error:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

More info here

Related