Creating an HTTP Server
A server is, it's a computer that's connected to internet.And in this case, for HTTP, for this protocol, you can request information or you can request to do something on a server from any other client.
And a client is anything else, it can be another server, it can be a front end app,it can be a mobile app, it can be anything that's connected to the internet.
So there's this whole mechanism of sending a request, and then the server responding to the request.So here's the incoming request, and then here's the response.
what a client is?
So 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.
If you've ever used Next Js, you've seen this before.Well, Next JS is heavily based off of Express,which is heavily based off on HTTP.
Node.js comes with everything you need to build a fully functional API. However, it's very tedious and unwise to use the raw modules. For context and appreciation of frameworks, let's do it anyway!
import http from "http";
const server = http.createServer(async (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" }));
});
const PORT = process.env.PORT;
server.listen(PORT, () => {
console.log(`server on ${PORT}`);
});
We have an API. It doesn't do much functionally, but it works. A client can issue a GET
request to the server at /
and get back some JSON. Any other request will yield a different message and a 404 status code.
We'll talk about HTTP Methods, status codes, and routes later in the course.
This code creates an HTTP server that listens on the port specified in the PORT
environment variable. It responds with a JSON object containing a message of "hello" when a GET
request is made to the root URL /
. If the request is anything else, it responds with a JSON object containing a message of "nope".