How to get an answer to a POST request using fetch?

I try so.

fetch('url', { method: 'post', body: 'body' }) .then ( (responce) ); 

  • If learn.javascript.ru/fetch is not deceiving, then: then .then(function(response) { return response.json(); }).then(function(responce) { alert(responce.field); }) where instead json may be other formats (text, json, formData, blob, arrayBuffer) - Alexey Shimansky
  • And what do you think this construct should do (responce) ? - Dmitriy Simushev

1 answer 1

The fetch method returns a promise . This promise will be fulfilled successfully (resolve) with the response object as an argument and rejected in case of an error. At this stage, there is absolutely no difference between POST and GET requests.

 fetch(request).then(function(response) { // Ответ получен. }).catch(function(error) { // Произошла ошибка. }); 

If necessary, you can perform any actions on the response object using its API .

Additionally, note that the response from the server with a code outside the range [200, 299] is not an error from the fetch point of view.


So, if we assume that the server returns data in JSON format, then we can use the following code:

 fetch('url', { method: 'POST', body: 'foo=bar' }).then(function(response) { // Стоит проверить код ответа. if (!response.ok) { // Сервер вернул код ответа за границами диапазона [200, 299] return Promise.reject(new Error( 'Response failed: ' + response.status + ' (' + response.statusText + ')' )); } // Далее будем использовать только JSON из тела ответа. return response.json(); }).then(function(data) { // ... Делаем что-то с данными. }).catch(function(error) { // ... Обрабатываем ошибки. });