Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between ServerResponse and http.IncomingMessage?

Tags:

node.js

what is the difference between ServerResponse and http.IncomingMessage? I'm new in Node,and I'm really confused about these two object.

like image 414
Cai Penny Avatar asked Jun 09 '26 07:06

Cai Penny


2 Answers

The http.IncomingMessage object represents the request information from the client received by the server. See this link for the Node API docs. So, this object contains things like the headers, the method (GET, POST, etc...), the URL requested, etc... It implements the ReadableStream interface -- which means you can read data from it using a stream -- and has several events, methods and properties. (too many to list here...)

The ServerResponse object represents the http server's response to the client. See this link for the Node API docs. With this object, you can set the headers that will be sent to the client, the status code and status message of the response, as well as any data to be returned. It implements the WritableStream interface -- which means you can write to it using a stream -- and also has several events, methods, and properties.

In many server side programs you'll see something like:

function foobar(req, res) {

}

The req variable holds the http.IncomingMessage object -- it's short for request. The res variable holds the ServerResponse object -- it's short for response.

Please see the documentation links for a full explanation of both objects.

Hope this helps!

like image 176
Jeff Kilbride Avatar answered Jun 11 '26 21:06

Jeff Kilbride


req is an IncomingMessage object and res is a ServerResponse object.

So check for unique properties on each, for example if the particular object has a writeHead() function, then it's the response object.

You may also be able to use instanceof to check: res instanceof http.ServerResponse.

like image 43
Shekhar Tyagi Avatar answered Jun 11 '26 20:06

Shekhar Tyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!