Showing posts with label Node JS. Show all posts
Showing posts with label Node JS. Show all posts

Saturday, 13 April 2019

Chapter : 1 - First code in Node JS


Previously I have written a blog about Getting Started with Node JS and its installation. Now lets start coding by making a simple server that listens at port 8085. We will make sure when request is made it displays "Hello, coders!" in browser.

Steps:


1. Open Visual Studio Code and create a file first_server.js .
2.  Write the code written below :-

    var http = require('http');
    http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h2>Hello, coders!</h2>');
   }).listen(8085);

Explaination of each line of Code :-


1) var http = require('http'); :-
It will include http module. http is a built-in module(set of methods to be included in application) that helps Node.js to transfer data over Hyper Text Transfer Protocol that enables server to listen to a particular port and get response back to client.

2) http.createServer :-
This method of http helps to create an HTTP server. It has a request argument that represent the incoming message usually denoted as req. The next argument is res which represents the response.

3) res.writeHead :-
It is used to define the response header. It has 2 arguments the first one is the status code and the second one is an object containing response headers.

4) res.end : -
It will end the response process.

5) .listen(8085); :-
Represent we want to listen to port 8085.



3. Use shortcut Ctrl + ` (Back-tick) to open the terminal in Visual Studio Code.
4. Write command in terminal <node first_server.js> and enter

5. Then go to browser and access the address - http://localhost:8085/


Congratulations, your first server is up and running.


Happy Coding folks!

Chapter : 1 - First code in Node JS Previously I have written a blog about Getting Started with Node JS and its installation. Now lets s...