Saturday 16 February 2019

Node.js: Express: Routing


Routing maps the url to specific handler based on the the URL and the http request type (GET, PUT, POST, DELETE etc.,).

Below statements map to home page.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'));

Whenever user request for /greetMe and get request, it is mapped to below function.
app.get("/greetMe", (req, res) => {
         console.log("Serving actual response");
         res.send("Hello User, Have a great day!!!!")
} );

Find the below working example.

HelloWorld.js
//Load express module
const express = require('express');

//Put new Express application inside app variable
const app = express();
app.count = 1;

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'));

app.get("/greetMe", (req, res) => {
 res.send("Hello User, Have a great day!!!!");
} );

app.get("/hello", (req, res) => {
 res.send("Hello!!!!!!!!!!!!");
} );

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Start HelloWorld.js application by executing below statement.
node HelloWorld.js

You can see below message in the console.
Application started listening on port 8080!


Hit the url 'http://localhost:8080/' in browser.

Hit the url 'http://localhost:8080/greetMe'.


Hit the url 'http://localhost:8080/hello'



Previous                                                 Next                                                 Home

No comments:

Post a Comment