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
|
2 Answers
Reset to default 12Promise.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)
.then(response => console.log(response.status))
is transforming the response toundefined
(the returned value ofconsole.log
) – Christian Vincenzo Traina Commented Sep 26, 2022 at 14:27