Reputation: 7952
onclick
function for a HTML5 button is implemented like below, to send some data to server with fetch
API. But I want to be able to receive data from server's response body. How can I do that:
function deleteUser(){
let confirmation=confirm('Are you sure?')
if(confirmation){
const req=new Request('/users/delete',{
method:'DELETE',
body:JSON.stringify({
email:this.getAttribute('data-email'),
mySay:'Looks like fetch is awesome'
}),
headers:new Headers({
'Content-Type':'application/json'
})
})
fetch(req).then(res=>{
//How can I receive data by server's response body?
console.log(res.body)
return res.json()
}).then(data=>{
console.log(data)
})
}else{
return false
}
}
On the server-side code, i.e. NodeJS with ExpressJS, I have the following code:
server.delete('/users/delete',(req,res)=>{
console.log(req.body)
//Server logs browser request body correctly:
//{ email: '[email protected]', mySay: 'Looks like fetch is awesome' }
//How can I send back response body from server to browser?
//The following method is NOT working:
return new Promise((resolve,reject)=>{
res.body=JSON.stringify({
msg:'I recieved your request'
})
resolve(res)
})
})
Upvotes: 1
Views: 1317
Reputation: 677
To send response use res.json():
res.json({
key: value,
key2: value2
})
Upvotes: 2