NodeJS Tutorial Day 4

Learning Objective: Let’s start with ExpressJS the most popular Module of NodeJS.

First, we need to install the express module into the current NodeJS working directory, for the same execute the following command:

npm i express

Hello World Example using ExpressJS

var express = require('express');
var app = express();

app.get('/', function(req, res){
   res.send("Hello world!");
});

app.listen(process.env.PORT || 8080);
node n1.js

Output:

Now Let’s Make a simple website with a few pages like Home, About Us, Services, and Contact Us.

var express = require('express');
var app = express();

app.get('/', function(req, res){
   res.send("<!DOCTYPE html> <html> <body> <a href='/'>Home</a> <a href='/about'>About Us</a> <a href='/contact'>Contact Us</a> <h1>Welcome to My Website</h1> <p><b>Important:</b> We Provides complete end to end services for IT Software Development and Training.</p> </body> </html>");
});

app.get('/about', function(req, res){
   res.send("<!DOCTYPE html> <html> <body> <a href='/'>Home</a> <a href='/about'>About Us</a> <a href='/contact'>Contact Us</a> <h1>About Us</h1> <p><b>Important:</b> We Provides complete end to end services for IT Software Development and Training.</p> </body> </html>");
});

app.get('/contact', function(req, res){
   res.send("<!DOCTYPE html> <html> <body> <a href='/'>Home</a> <a href='/about'>About Us</a> <a href='/contact'>Contact Us</a> <h1>Contact Us</h1> <p><b>We are Available 24 * 7 to Help you. </p> </body> </html>");
});


app.listen(process.env.PORT || 8080);

URL List

Home Page - http://localhost:8080/
About Page - http://localhost:8080/about
Contact Page - http://localhost:8080/contact

Here is the Output:

Now Let’s collect user details using Form

Let me change Contact Us Page with HTML Form

app.get('/contact', function(req, res){
   res.send('<!DOCTYPE html><html><body> <a href="/">Home</a> <a href="/about">About Us</a> <a href="/contact">Contact Us</a> <h1>Contact Us Now</h1><form action="/contact2">      <label for="fname">First name:</label><br>     <input type="text" id="fname" name="fname" value="Adarsh"><br>     <label for="lname">Last name:</label><br>     <input type="text" id="lname" name="lname" value="Patel"><br><br>     <input type="submit" value="Submit">   </form> <p>If you click the "Submit" button, the form-data will be sent to a page called "/contact2".</p>   </body> </html>'); 
});

Now Contact Page will look Like:

On Click of Submit button, form data will be submitted to /contact2 URL

You need to update contact2 code with the following to display a message above. (Here I am extracting parameters from the URL and displaying on screen)

app.get('/contact2', function(req, res){
   res.send('Your First Name is: ' + req.query['fname'] + "\nYour Last Name is: " + req.query['lname']); 
});