rohan
rohan

Reputation: 81

http.request vs http.createServer

What is the difference between the request in this line of code:

http.createServer(function(request,response){. . .}

and request in

http.request()

Are both requests done to the server?

I am new to node.js and I am sorry if I sound dumb!

How does http.request() work?

In http.request() we fetch data from another site but in order to fetch data from another site we first need to go to our site and then make a request? Explain it with a simple real-life example!

Upvotes: 0

Views: 2011

Answers (2)

Brad
Brad

Reputation: 163593

http.request() makes a request to another HTTP server. Suppose for some reason I wanted to go download Stack Overflow's home page...

http.request('https://stackoverflow.com/', (res) => {
  // ...
});

http.createServer()... it creates an HTTP server. That is, it binds your application to a socket to listen on. When a new connection is made from somewhere or something else, it handles the underlying HTTP protocol of that request and asks your application to deal with it by way of a callback. From the Node.js documentation:

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});

These two methods have absolutely nothing to do with each other. http.request() is for making a request to an HTTP server. http.createServer() is for creating your own HTTP server. Don't get confused by the callbacks.

Upvotes: 5

yodebu
yodebu

Reputation: 167

Based on the source code of nodejs (extract below), createServer is just a helper method to instantiate a Server.

Extract from line 1674 of http.js.

exports.Server = Server;


exports.createServer = function(requestListener) {
  return new Server(requestListener);
};

The http.request() API is for when you want your server code to act as a client and request content from another site and has GET, POST, PUT, DELETE methods.

Upvotes: -1

Related Questions