如何使用fetch().then()获取响应体

问题描述 投票:0回答:2

我需要一个

const
来定义这个主体(字符串)。然后我可以用它来做类似的事情
console.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)));

enter image description here

javascript fetch-api
2个回答
6
投票

Promise.then
可以链式
Promise.then
参数是从之前的
Promise.then
链返回的对象

Response.text()
返回字符串体

Response.json()
返回解析后的json

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

2
投票

您可能正在寻找 Response.text():

fetch(url,...).then(response => response.text()).then(console.log)
© www.soinside.com 2019 - 2024. All rights reserved.