1

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)
        })
})

1 Answer 1

2

To send response use res.json():

res.json({
   key: value,
   key2: value2
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.