Issue
I am trying to get data from Node.js in my javascript as part of a task.
The node.js
app.get('',(req,res)=>{
res.render('index.ejs')
})
app.get('/calculateResult',(req,res)=>{
console.log(id)
res.send(5)
})
The javascript file is a linked script in the index.ejs.
The js
const pullLever = async function(){
let response = await fetch('/calculateResult')
alert(JSON.stringify(response,null,4))
}
I expect five(5) to be contained in the alert response whenever the ‘pullLever’ function is called, but with this code the response is just an empty dictionary({}), any help will be much appreciated
Solution
the JSON.stringify(response,null,4)
returns {} because response
is not return response body, but Response
object. if what you want is get the response body, you should Response.text()
it (or Response.json()
it).
const pullLever = async function() {
const response = await fetch('/calculateResult');
const text = await response.text();
alert(JSON.stringify(response, null, 4));
}
or
const response = await fetch('/calculateResult').then((val) => val.text());
and why does Response object can’t be stringified? Response’s fields is private. I guess.