在ExpressJS中编辑响应

时间:2014-03-10 08:42:01

标签: javascript node.js express middleware

我试图在Express中编辑对请求的响应。当请求是XHR请求时,我想在JavaScript对象中返回正文(这最终会将页面的不同部分作为JavaScript对象中的不同部分返回,即{ header: '<header></header>', footer: '<footer></footer>' }

我似乎无法找到响应对象的哪个部分包含实际响应。这是我认为我想要去的方向,但我无法让它发挥作用。

app.use(function(req, res, next) {

    res.on('send', function() {

        if(req.xhr) {
            //if the page is requested with ajax, return JSON
            res.body = {body: res.body};   
        }

    });

    next();
});

1 个答案:

答案 0 :(得分:1)

你可能想要修补发送方法

app.use(function(req,res,next){
    var send=res.send;
    res.send = function(){
        //use the arguments here to get your body out (won't always be the first property if there's a response code passed through)
        console.log("Sending",arguments); 
        send.apply(res,arguments);
    }
    next();
})

查看response.send方法的源代码,了解如何解析参数。 https://github.com/visionmedia/express/blob/master/lib/response.js#L81