What is HTTP and how to create a HTTP server in pure Node.js (no framework)
Frameworks or libraries are good since it accelerate the development speed, but they are not beneficial if you want to know what exactly goes on behind the scenes. So I want to create a HTTP server in pure Node.js without frameworks like Express.
What is HTTP?
Before jumping to create the server, we need to understand what is HTTP. It standards for Hyper Text Transfer Protocol which defines the communication rules between client and server, the client is usually a browser sending requests, a server is a computer holding the resource or files you want.
HTTP Request & Response Process
As we can see in the picture below(send the request using Postman), after we sending the request, a socket is initialized, then mapping the domain name we typed in, for example, “www.google.com” is translated to “172.217.25.132”, after TCP connection and secure socket layer are established, the server starts to transfer the file we want.
HTTP Header
It is very important to know how HTTP request/response looks like. We can go to the Chrome developer tools, click the “network”, after typing “www.google.com” in the browser address bar, a bunch of files are sent back to us. On the right is the header information,
General information like the URL we request, request methods(Get, Post,Put, Delete are main methods), status code(2xx means success, I bet you come across 404 before, 4xx is client error, 404 means your request is not correct directing to a file that does not exist, 5xx is server error) check the response/request header we could also see content-type, date, user-agent, etc. Together with the header, there are request body and response body, and these are what we actually what to transfer. Before sending request or response, we need to set the header and body correctly according to HTTP protocol as we seen.
Set Up HTTP Server in Node.js
Before writing the JavaScript file, make sure you have Node.js installed, type in “node -v” to check
(base) renees-MacBook-Pro:httpServer renee$ node -v
v12.13.1
create a JavaScript file wherever you want, I name this file “server.js”, in the terminal type “node server.js”, you should see “server is listening on port 5000” in the terminal. Node.js provide us a http module, we can use the method “createServer()” to set up our server, and let it listen to port 5000.
const http = require("http");const server = http.createServer((request, response) => {
// we process request and response here
});server.listen(5000, () => {
console.log("server is listening on port 5000");
});
Then, we could process the request and response
const http = require("http");const server = http.createServer((request, response) => {
// we process request and response here
const { method, url, headers } = request;
const userAgent = headers["user-agent"];
console.log(userAgent);
});server.listen(5000, () => {
console.log("server is listening on port 5000");
});
Now, if you open Postman, send a request to “localhost:5000”, you should see the userAgent in the termial like this, because we use Postman, send the request through browser you should get the name of the browser. The new 3 lines of code is just use ES6 deconstruct syntax to get the object properties, here we get the “userAgent” property.
But we does not send back any response, let’s add the response.
const http = require("http");const server = http.createServer((request, response) => {
// we process request and response here
const { method, url, headers } = request;
const userAgent = headers["user-agent"];
console.log(userAgent);response.writeHead(200, {
"Content-Type": "application/json",
"X-Powered-By": "Renee"
});
const responseBody = { env: "Node.js" };
response.write(JSON.stringify(responseBody));
response.end();});server.listen(5000, () => {
console.log("server is listening on port 5000");
});
If you use Postman, you should see the JSON message we send back to the client.
It is this simple, we edit the header and body of the response in the format HTTP protocol defines, so we can communicate through internet in this client-server way. In the future, we can use different request method like POST(binding message on requests, then send to server), we could also transfer different format of files, not just JSON file, but JSON is easier to handle, we could send back a much more informative JSON than this one through.