最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use fetch().then() to get Response body - Stack Overflow

programmeradmin4浏览0评论

I need a const to define this body(string). Then I can use it to do like 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)));

I need a const to define this body(string). Then I can use it to do like 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)));

Share Improve this question edited Feb 15, 2024 at 19:51 VLAZ 29k9 gold badges62 silver badges83 bronze badges asked Sep 26, 2022 at 14:15 Phosphorus redPhosphorus red 1011 gold badge1 silver badge6 bronze badges 2
  • Could you elaborate a little more? What do you want to achieve? This question is not clear at all. – Tristan T. Commented Sep 26, 2022 at 14:23
  • 1 .then(response => console.log(response.status)) is transforming the response to undefined (the returned value of console.log) – Christian Vincenzo Traina Commented Sep 26, 2022 at 14:27
Add a comment  | 

2 Answers 2

Reset to default 12

Promise.then can be chained Promise.then parameter is object returned from previous Promise.then chain

Response.text() return string body

Response.json() return parsed 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

You are probably looking for Response.text():

fetch(url,...).then(response => response.text()).then(console.log)
发布评论

评论列表(0)

  1. 暂无评论