Request
- A client can make a request to attempt to do something on a server, and then the server typically has to respond to that client, and then the connection is closed.
- If the server doesn't respond, the connection typically times out on whatever limit that the client decided for that timeout period.
Response
Response is just for sending things back.And then how do they get passed to the callback? Well, that is the job of this HTTP module.When it creates a server, it's basically saying,you can think of it as an event-driven architecture.
So when someone makes a request to a server, that's an event.
Just like if you were to make a button.addEventListener
, right,you would say I wanna add an event listener on this button.And the event that I'm gonna register for is called the click event.And when a click event happens, run this callback.That's the same thing.The event in this case will be an incoming request.And we want to run this callback when the request comes in.
(req, res) => {
if (req.url === "/" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.write(JSON.stringify({ message: "hello" }));
res.end();
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "nope" }));
};
Your server's gonna get millions of request.How would you know which request to respond to?.This response objects is scoped to the incoming request.So if this function runs a million times per second, this response object is guaranteed to be scoped to this instance of the request that's running.