0

After sending response I'm calling next() which goes to my post middleware. Where I want to get data which I'm sending data in response.

res.status(200).json({username: 'abc'}); next()

now In post middleware I want to access that data.

I have tried res.on('data' ,function(chunk){}) but no luck. also if do res.someProperty = "some data" it works fine.

But i cant do in case of json as my code already written I have to fetch that data using middleware as i have 100s of routes and i dont want to change each. So the only way to access data is by using middleware.

So my purpose is to get data added in json. something like res.username or res.data.username.

App.js middleware code

//pre-middleware
app.use(function(req, res, next){
    res.on('data', function(err, data){
        if(err) console.log(err);
        console.log('data', data);
    })
    console.log('######pre status', res.statusCode);
    next();


});

app.use('/', index);

//post-middleware
app.use(function(req, res, next){
    console.log('###########post');
    console.log( 'response', res.statusMessage);


})

index.js get router code

router.get('/middleware', function(req, res, next){

    res.status(201).json({
        username: 'awais'
    });

    next();

});

Someone add solution related to printing body and I mention that first I don't want to print body of response secondly those solution tried and not working.

owais
  • 4,752
  • 5
  • 31
  • 41
  • You can't call `next` after `res.json`, because the response is already created and couldn't be changed. – alexmac Aug 16 '17 at 10:58
  • please add whole code piece – Arel Sapir Aug 16 '17 at 10:58
  • @alexmac I'm calling as I told if i attach some property i can recievie that in post middleware. – owais Aug 16 '17 at 11:00
  • @alexmac calling `next` is *technically* ok, if you can guarentee that nothing will affect the response from thereon in. – James Aug 16 '17 at 11:11
  • 2
    Possible duplicate of [express logging response body](https://stackoverflow.com/questions/19215042/express-logging-response-body) – James Aug 16 '17 at 11:15
  • @James I don't have to print body I'm saying what JSON is adding. to response and where. – owais Aug 16 '17 at 11:20
  • 2
    @owaishanif786 it doesn't matter what you want to do with it, the linked answer is doing what you need which is intercepting the response data (it just so happens to be logging it). Not sure you understand that when you call `json` the data is piped out to the response immediately, the data isn't held anywhere in the response object therefore you need to intercept it whilst it's being written. – James Aug 16 '17 at 11:58
  • There's also existing middleware that can help you: https://github.com/kapouer/express-buffer-response However, I'm inclined to vote close as well, as it _is_ a duplicate. Instead of logging, you can modify the answer to do whatever else you want to do with the response data. – robertklep Aug 16 '17 at 14:27

0 Answers0