Use Node.JS as a Web Server
In this article, we will discuss about using the Node.JS API to handle basic server functions like GET and POST. An even simpler way to write server code is through a framework called express (update: I’ve used express framework here.) I will write tutorials about that in the coming articles when we get the core idea on handling basic web server functions
To create a web server with the HTTP module in the Node JS engine, we need to use the following method:
Here, the callback will take two arguments; a request and a response. The request argument will send data from the client to the server so that the data can be processed, after which the response is sent to the client from the server.
The most basic example can be:
The code can even be further shortened. You can replace res.write() and res.end() with :
res.end('Hello World') //Write response AND then end it
Run the code through the command line. If you don’t get any words printed on the terminal, that’s normal. You should get your result by going to your browser and typing:
And the words ‘Hello World’ will be printed out on the screen
Specifying The Header
response.writeHead() sends header response to the request. Or used to set the status code and create HTTP headers.
If you want to specify the server response to be displayed in HTML. You need to tell the header that the content type should be HTML
The first parameter of the res.writeHead() is the response code. It can be 2xx, 3xx,4xx, or 5xx.
The second parameter is the options. Here we specified that the content type is HTML i.e our response will be displayed in HTML format, and that the length of the content will be equal to the length of your body.
You can even change headers using the response argument properties:
response.writeHead = 400
HTTP Server Requests
The req parameter of the http.createServer method has all the information about the incoming request for eg. request payload, headers, URL etc.
req parameter has the following properties
request.headers: Information about the request headers such as Connection, Host, Authorization, etc.
request.method: Information about the incoming request methods such as GET, POST, PUT, DELETE, OPTIONS, HEAD, etc.
request.url: Information about the incoming request URL, such as
/accounts, /users, /messagesetc
Processing Incoming Request Body in the Server
Let’s say that the client has sent data, how do we process it?
Executing this code requires a bit different way:
If you are on Windows, first you need to install a tool called cURL and then run the code through the command line.
To send data, open another command line window, and write:
curl -x POST -d “key-value” localhost:3000
Another alternative to cURL is Postman
On your previous command line window, you will find the data that you sent through cURL. In this case, it is