質問

I'm trying to edit the response to a request in Express. When the request is an XHR request, I want to return the body inside a JavaScript object (this would eventually return different parts of the page as different pieces in the JavaScript object, i.e. { header: '<header></header>', footer: '<footer></footer>' }.

I can't seem to find which part of the response object holds the actual response. This is the direction I think I'm meant to go, but I can't get it to work.

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();
});
役に立ちましたか?

解決

You'll probably want to monkey-patch the send method

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

look at the source for the response.send method to find out how to parse the arguments. https://github.com/visionmedia/express/blob/master/lib/response.js#L81

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top