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

Pho*_*red 2 javascript fetch-api

我需要一个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)));
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 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
Run Code Online (Sandbox Code Playgroud)