Cómo usar fetch().then() para obtener el cuerpo de la respuesta

Resuelto delete asked hace 1 año • 0 respuestas

Necesito un constpara definir este cuerpo (cadena). Entonces puedo usarlo para hacer comoconsole.log()

fetch("url", {
            headers: {
                "Content-Type": "application/json",
                'Authorization': 'Basic ' + btoa(globalUsername + ":" + globalPassword),
            },
            method: "POST",
            body: moveBody
        }).then(response => console.log(response.status)).
        then(response => console.log(response.text(body)));

ingrese la descripción de la imagen aquí

delete avatar Sep 26 '22 21:09 delete
Aceptado

Promise.thenEl parámetro se puede encadenar Promise.theny es un objeto devuelto de Promise.thenla cadena anterior.

Response.text()cuerpo de cadena de retorno

Response.json()devolver json analizado

fetch("url", {
    headers: {
      "Content-Type": "application/json",
      'Authorization': 'Basic ' + btoa(globalUsername + ":" + globalPassword),
    },
    method: "POST",
    body: moveBody
  })
  .then(response => console.log(response.status) || response) // output the status and return response
  .then(response => response.text()) // send response body to next then chain
  .then(body => console.log(body)) // you can use response body here
kennarddh avatar Sep 26 '2022 14:09 kennarddh

Probablemente estés buscando Response.text() :

fetch(url,...).then(response => response.text()).then(console.log)
Jan Turoň avatar Sep 26 '2022 14:09 Jan Turoň