【问题标题】:How to send-back some data from server to browser with fetch API's response body如何使用获取 API 响应正文将一些数据从服务器发送回浏览器
【发布时间】:2017-12-27 19:00:50
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    使用 res.json() 发送响应:

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

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多