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

标签 javascript fetch

我需要一个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

最佳答案

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

关于javascript - 如何使用 fetch().then() 获取响应正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73855468/

相关文章:

javascript - 当我将鼠标悬停在“产品”菜单上时,此代码需要进行哪些更改以提供正确的外观?

javascript - KonvaJs:为箭头添加边框

javascript - Next.js 数据获取 useSWR 还是使用 useEffect 进行常规 fetch/axios?

Java JDBC 获取表

javascript - 正常的 GET 请求在 Chrome (API) 中不起作用

javascript - 通过 WebAssembly 将 Rust Vec<Vec<i32>> 返回给 JavaScript

javascript - 代码在 codeSandbox 中运行良好,但在 IDE 中执行时显示错误 "can' t define property "email": Object is not extensible"

javascript - 尝试从 json 文件中获取数据时出现问题

java - 如何在 join fetch QueryDSL JPAQuery 中进行选择?

javascript - 如何在 Angular 6 中设置背景图像图像路径