# Node.js #2 Using expressjs framework for web development ## What is expressjs Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. We will use this framework becouse it has helper functions, tools and rules that help you to build your application and focus on the bussnuies logic. ## Install express, nodemon libs nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. `npm install --save-dev nodemon` `npm install --save express` ## Start express The following code, will import http, express libs, create express app and inject the app to http server with port 3000 ```=javascript const http = require("http"); const express =require("express"); const app = express(); const server = http.createServer(app); server.listen(3000); ``` ## add Middleware Middleware is functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next. ![](https://i.imgur.com/ZdpflOQ.png) ```=javascript app.use((req, res, next) => { console.log("this is middleware"); next(); }); app.use((req, res, next) => { console.log("this is another middleware"); res.send('<h1>Hello world!</h1>') }); ``` ## Manage Routes We can manage the routes by using middleware ```=javascript app.use('/', (req, res, next) => { console.log("this is another middleware"); next(); }); app.use('/home', (req, res, next) => { console.log("this is another middleware"); res.send('<h1>Home Page</h1>'); }); app.use('/add-product', (req, res, next) => { console.log("this is another middleware"); res.send('<h1>Add Product</h1>'); }); ``` ## Using express router ```=javascript const adminRoutes = require("./routes/admin"); const productRoutes = require("./routes/product"); app.use(adminRoutes); app.use(productRoutes); ```