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) { // ... Обрабатываем ошибки. }); 
  • Well, put a string in body json - Alexey Shimansky
  • @ Alexey Shimansky, thong same? - Grundy
  • @Grundy yep .... - Alexey Shimansky

2 answers 2

FormData in which there will be a field with necessary json in the form of a line (JSON.stringify)

 // как пример для отсыла данные var myData = { a: 1, b: 2 }; var data = new FormData(); data.append("json", JSON.stringify(myData)); fetch("url", { method: "POST", body: data }).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) { // ... Обрабатываем ошибки. }); 

Another option is to give json in the body:

 fetch('url', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: 'json=' + JSON.stringify(myData) }) ... ... 

json= - just to identify the key on the server, but you can without it.


peeped on enSO and enSO

  • Twice to encode the data - a perversion - andreymal
  • @andreymal, where is the second time? - Grundy
  • @Grundy data.append - right here - andreymal
  • one
    @ AlekseyShimansky why not ? - Andreymal
  • one
    @vp_arth yeah them in the swamp) - Alexey Shimansky

It is enough just to pass json as the request body:

 fetch('http://httpbin.org/post', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({a: 7, str: 'Строка: &=&'})}).then(res=>res.json()) .then(res => console.log(res));