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)
})
})
Copyright Notice:Content Author:「user3405291」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45242518/how-to-send-back-some-data-from-server-to-browser-with-fetch-apis-response-body