W
W
Wasya UK2018-02-20 22:16:01
HTML
Wasya UK, 2018-02-20 22:16:01

How to make a normal request in fetch?

I decided to try fetch, but when I try to get the server response data, I get not very beautiful code. Is there a better way to write?

document.querySelector('#login-form').onsubmit = function (e) {
      e.preventDefault();
      fetch('/login', {
        method: 'POST',
        body: 'Hello'
      }).then(function(response) {
        return response.json();
      }).then(function(result) {
        alert(result.data);
      });
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-20
@rockon404

You can use axios

axios.post('/login', { body: 'Hello' })
  .then(function(res) {
    alert(res.data);
  });

Requests to the north are well formatted with separate functions:
ES5 version:
const login = function(options) {
  return axios.post('/login', options);
}

Its use in code: ES5 version:
login(options).then(function(res) {
  alert(res.data);
});

in async function:
async () => {
  try {
    const { data } = await login(options);
    /* some other logic */ 
  } catch e {
    console.log('Server request error:', e);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question