Beyond Hello World with NodeJS | 1.1 | The Simplified way

In  my Last article,we made a simple server using that responds with "Hello World". you can follow the previous article Understanding NodeJS and Hands On | The Simplified Way 

In this article we are going to create something beyond just "Hello World", we are going to talk about installing 3rd party modules using npm and using it in our node application to make things easier.

Firstly we will will start with most popular server side framework "ExpressJS", It is a JS framework which makes the things easier for us, let watch it in action.

Till now our project directory contains only 2 files that is "index.js" and "package.json" and we have not used any 3rd party module in our application.



Now we will install "Express JS" as third party dependency module from NPM, and will make a server which return different kind of response on different requests.

Step 1: Open your terminal in your project directory and run the command "npm install express --save" and wait till it finishes downloading the module from npm registry, it will look like the below screenshot.


Now have a look at the folder structure of your project you will see a new folder "node_modules", this is the folder that contains all the 3rd party modules installed from npm, most of the time you don't need to touch this folder. and in "package.json" you will notice that express is added as dependency, as shown in the below screenshot.


Step 2. Now its time to use it in "index.js" that is our server, to minimize confuse clear the complete "index.js" file, we will start from scratch, write these six line of code and your hello world server is ready! (You can copy and paste the below code it is not a screenshot)


const express = require('express')
const app = express()
//defining default route for "/" 
app.get('/', (req, res) =>
{ 
  res.send('Hello World! from Express')
});
app.listen(3000, () => console.log('Server Started on localhost:3000'))

without using express, we need to write more complex code as we have seen in the previous article.

Code Explanation
Line 1: Including the 'express module' and assigning it to a variable called "express".
Line 2: Initializing the express application and assigning it a variable called "app
Line 3,4,5: We are defining the route with get request format that is '/' and calling an anonymous function which accepts req and res object  that responds with the text ' Hello World! from Express'

Line 6: We are finally starting our server which is listening on port 3000. 

Step 3: Now its time to test hello world with express, open the terminal in project directory (make sure you have saved the file) and run "node index" as shown below: 


Now open "http://localhost:3000/" in your browser and see your work in action, as shown in the below screenshot.


Congrats, you have made your first Server with Express in just 4 line of code!

Now its time time to go beyond just sending "Hello world", we are going to talk about different type of response and data that we can use:

1. HTML formatted Response:

  • Made the index.js like the below code you can notice the one line change i.e " <h1>Hello HTML Heading</h1>" in res.send , as shown in the below code snippet.
1
2
3
4
5
6
const express = require('express')
const app = express()
app.get('/', (req, res) =>{ 
res.send('<h1>Hello HTML Heading</h1>')
});
app.listen(3000, () => console.log('Server Started on localhost:3000'))
  • Save your code and re-run your server using the  terminal as shown in step 3(above).
  • Open http://localhost:3000/ and see the magic.it will look like the below screenshot.


           
2. JSON formatted Response

  • While working with real life project we use JSON as standard format for transferring the data. instead of sending simple plain and HTML formatted response we can also return JSON reponse, let try this one with a dummy json data.
  • Add a new route "/users" which will return a json array containing dummy user data, add the line 8-25 from below code snippet and you complete index.js will look something like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const express = require('express')
const app = express()
//defining default route for "/" 
app.get('/', (req, res) =>{ 

res.send('<h1>Hello HTML Heading</h1>')
});
//Line 8 : defining route for "/users"
app.get('/users', (req, res) => {
let users = [{
                    first_name: "Suraj",

                    last_name: "Kumar",
                    age: 22,
                    gender: "male"
                   },
                   { 

                     first_name: "Vrijraj",
                     last_name: "Singh",
                     age: 24,
                     gender: "male"
                    }];
res.json(users);
}); //Line 25
app.listen(3000, () => console.log('Server Started on localhost:3000'))



  • Again Save and re-run your server from terminal using the command "node index" and open "http://localhost:3000/users" in your browser , you will a JSON array as response as shownin the below screenshot.

  •   This is how we can send JSON data as a response.


 3. Redirecting to other URL

  • In many situation instead of sending response back we want to redirect a request to a URL, again it very simple just add a route to your server (index.js), and instead of res.send just use res.redirect as shown in the below code snippet.

1
2
3
app.get('/facebook', (req, res) => {
res.redirect('https://www.facebook.com/');
});

Save your Code ,Re- run your server from terminal and open "http://localhost:3000/facebook" it will redirect you to facebook.

Great, you have learnt a lot in this article, In the Next Article we are going to make a simple fully functional multipage website using express and some other module.

After doing all these the final Code of "index.js" will look like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const express = require('express')
const app = express()
//definiing default route for "/" 
app.get('/', (req, res) =>
{ 
  res.send('<h1>Hello HTML Heading</h1>')
});
// defining  route for "/users"
app.get('/users', (req, res) => {
  let users = [
    {
      first_name: "Suraj",
      last_name: "Kumar",
      age: 22,
      gender: "male"
    },
    {
      first_name: "Vrijraj",
      last_name: "Singh",
      age: 24,
      gender: "male"
    }
  ];
  res.json(users);
});
//route for URL redirect
app.get('/facebook', (req, res) => {
  res.redirect('https://www.facebook.com/');
  });

app.listen(3000, () => console.log('Server Started on localhost:3000'))

If you face any problem feel free to ask in comments//

Keep Expressing!!!

Comments

Popular posts from this blog

Evolution of Internet of Things(IoT)

Developing a Progressive Web App from a Static Web App.

Building a Progressive Web Apps- CodeLab