Saturday 18 January 2020

Express.js in 5 mintues | Node.js

npm install express

my fist HelloWorld application.

var express=require('express');    //use the express module
var app=express();     // create an object of express module
app.get('/', function (req,res){ //create a call back function
    res.send('helloworld'); //send helloworld response
});
var server = app.listen(3000, function(){ make the server listen on 3000
   
});
----

1. using require function we are including the express module.
2. we need to make an object for the express module we just included.
3. create a callback function to be called whenever the user hits our root (/)
4. in the callback function, we are sending a response to the user
5. call a listen to function to make our server listens to client requests on port 3000.
done. use this web address to confirm.
localhost:3000/

Route (/):
routes reads clients input and responds to the request. say GET,POST,PUT,Delete

localhost:3000/
localhost:3000/books
localhost:3000/students

in above,
we used get method (app.get while calling a callback function)
the syntax was like this:
app.METHOD( PATH, HANDLER)

the app is an instance of express
the method is an HTTP request method like GET, POST, PUT, DELETE)
PATH is a path on the server, like route (/), /books
HANDLER is the call back function executed when the route is matched.


let's look with 3 examples:
/node route will display "hello node"
/angular route will display "hello angular"
/ route will display "hello buddy"

app.route('/node', get(function(req,res){
    res.send("hello node");
} ));
app.route('/angular', get(function(req,res){
    res.send("hello angualr");
});
app.get('/',(function(req,res){
    res.sed("hello buddy");
});

3 comments:

  1. Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
    Mean Stack Training in Chennai
    React JS Training in Chennai

    ReplyDelete
  2. Thanks for sharing valuable information about Express.js in 5 mintues | Node.js, keep posting Java Course In Pune

    ReplyDelete
  3. Thanks for sharing this informative article on Express.js in 5 mintues | Node.js. If you want to mean stack development company for your project. Please visit us.

    ReplyDelete