Now we are going to learn the easy way -> Express


what and why



server logic is complex ->
    ex- parse incoming request
            we have to manually listen for data event
            end event
            create a buffer
            convert to string
            just to get one type of data.. imagine you want to get a file.. crazy hah?
   
    for easily manage these -> introduced express js

   
install production dependency
 npm install --save express



Adding Middlewares

const express = require("express");

const app = express();

app.use((req, res, next) => {            //This is a middleware
  console.log("In the Middleware");
  res.send("<h1>Hello From Node JS server</h1>");
});

app.listen(3000);

console.log("Server running at http://127.0.0.1:3000/");

 

  • Middleware is used for getting requests sending responses and calling to other middlewares set routings and many more

 

Explanation ->


//const http = require("http"); //... warning comes unfortunatly es6 
is not supported by browsers yet const express = require("express"); const app = express(); //Middlewares //used for every incoming request app.use((req, res, next) => { console.log("In the 1st Middleware"); next(); //Allows to calls the next middleware (middleware2) //if we diidnt call it -> request will die }); app.use((req, res, next) => { console.log("In the 2nd Middleware"); //res.setHeader() can set headers res.send("<h1>Hello From Node JS server</h1>"); //allows to send a response //express set the headers automatically //we can also set manually by-> res.setHeader() }); // const ser ver = http.createServer(app); // server.listen(3000); //also removed import //both lines in above can be replaced with app.listen(3000); console.log("Server running at http://127.0.0.1:3000/");