How to get an answer to a POST request using fetch?
I try so.
fetch('url', { method: 'post', body: 'body' }) .then ( (responce) ); How to get an answer to a POST request using fetch?
I try so.
fetch('url', { method: 'post', body: 'body' }) .then ( (responce) ); 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) { // ... Обрабатываем ошибки. }); Source: https://ru.stackoverflow.com/questions/505987/
All Articles
.then(function(response) { return response.json(); }).then(function(responce) { alert(responce.field); })where insteadjsonmay be other formats (text, json, formData, blob, arrayBuffer) - Alexey Shimansky(responce)? - Dmitriy Simushev