h2non / rocky

Full-featured, middleware-oriented, programmatic HTTP and WebSocket proxy for node.js (deprecated)
MIT License
371 stars 24 forks source link

How to access upstream response's statusCode in response middleware callbacks? #113

Closed h6ah4i closed 7 years ago

h6ah4i commented 7 years ago

Hi. Thanks for the superb library, it's very handy and useful! However, I am just struggling the behavior of useResponse() callback now.

What I want to do

I want to change the response body according to statusCode of upstream. However, the res.statusCode is always 200 in useResponse callbacks. Is this intended behavior?

proxy
   .get('/:filename')
   .useResponse((req, res, next) => {
     if (res.statusCode == 200) {  // <-- res.statusCode is always 200
       res.body = "xxx";
     } else {
       res.body = "yyy";
     }
     ...
   }

Hack

I dug into the rocky library and found that the headArgs variable holds the original status code which I need. I tweaked the lib/middleware/response-body.js like following;

    res.end = function (data, encoding) {
      ...

      // Restore native methods
      restore()

+     if (headArgs) {
+       res.statusCode = headArgs[0];
+     }

      // Trigger response middleware stack
      middleware(req, res, partial(finisher, cb))
    }

I am not sure whether this modification is good or bad, so I've not created a pull request yet :(

Thanks.

h2non commented 7 years ago

Wow. I suspect this is a change in nodejs internals in latest versions. I don't know why that happens, the statusCode property should be defined when calling response.writeHead() method :S

Anyway, I have fixed this. Try upgrading rocky to v0.4.15:

$ npm update rocky --force

Thanks for reporting the issue.

h6ah4i commented 7 years ago

Thanks for a quick response 😄