如何使用fetch API的响应主体将一些数据从服务器发送回浏览器

时间:2017-07-21 16:27:02

标签: javascript node.js ajax xmlhttprequest fetch-api

HTML5按钮的

onclick功能如下所示,通过fetch API将一些数据发送到服务器。但我希望能够从服务器的响应机构接收数据。我怎么能这样做:

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

在服务器端代码,即带有ExpressJS的NodeJS上,我有以下代码:

server.delete('/users/delete',(req,res)=>{
        console.log(req.body)
        //Server logs browser request body correctly:
        //{ email: 'bob@smith.io', 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 个答案:

答案 0 :(得分:2)

要发送回复,请使用res.json():

res.json({
   key: value,
   key2: value2
})