0

I'm having an issue with a node app I've written using express. In order to help debug the issue, I want to print out every HTTP message that the app sends or receives to the console. I've tried this:

app.use('/', (req, res, next) => { console.log(req) console.log(res) next() }) 

But the issue is the objects res and req that get printed here don't include the info I need. They are an HTTP.ServerResponse and HTTP.IncomingMessage object, respectively. There is no body element in res (i.e. the response my app is sending), and I can't figure out how to get it. I've tried this as well:

app.use('/', (req, res, next) => { var data = '' res.on('data', chunk => { data+=chunk }) res.on('end', () => { console.log(data) next() }) }) 

But that causes the server to hang. next() never gets called.

How can I do what I want?

2
  • 1
    Try to use on-finished module. It attaches a listener to listen for the request or response to finish. Commented Oct 10, 2017 at 20:55
  • @alexmac this worked, sort of. I was able to get it to print out the response object, but I still can't figure out how to get the body of the response. Commented Oct 10, 2017 at 21:07

1 Answer 1

1

When defining a use handler you absolutely must call next before the processing of that request continues. Here you've sabotaged yourself: You never call it until the request is finished, but that's never going to happen since you never call next in the first place.

What you want is probably this:

app.use('/', (req, res, next) => { var data = '' res.on('data', chunk => { data+=chunk }) res.on('end', () => { console.log(data) }) next() }) 

Not calling next is the way you say "Wait, I'm not done yet!" but what you want is to set up those hooks and then resume processing.

Sign up to request clarification or add additional context in comments.

6 Comments

I tried this, and nothing ever gets printed. I know for a fact that at least one of the responses that I'm sending has a body, so I should be seeing something. I added a debug inside the 'data' hook, and it never gets called.
Does this hook ever get called? You should try without the path specifier to make sure it's a generic hook and not a path specific one.
the hook in general does get called every time I receive a request. I know that because the original hook prints out the entire ServerResponse object
I have a feeling that's a different problem. Your question pertains to it jamming up your request and preventing it from finishing. If you've got another one about hooking into the res and capturing data, that's a different question. Your res object is probably not emitting the events you think it is. That's what req does.
I get what you're saying, but I think this is another question now that the next() issue has been resolved.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.