Working with Express.js
Whats in the module :
What is Express.js :
Installing Express.js: To install the expressjs into your app , you have to run - npm install --save express
Adding Middleware:
example :
const http =require('http');
const express = require('express');
const app = express();
app.use((req , res , next)=>{
console.log('In the middleware!');
next();//Allow the request to continue to the next middleware in line
});
app.use((req , res, next)=>{
console.log('In another middleware!');
})
const server = http.createServer(app)//app is act As a valid request handler.
//listening to a port for request
server.listen(3000);
console.log('listening to port 3000');
Handling Different Routes :
const express = require('express');
const app = express();
// app.use((req, res, next) => {
// console.log('First Middleware');
// next();
// });
// app.use((req, res, next) => {
// console.log('Second Middleware');
// res.send('<p>Assignment solved (almost!)</p>');
// });
app.use('/users', (req, res, next) => {
console.log('/users middleware');
res.send('<p>The Middleware that handles just /users</p>');
});
app.use('/', (req, res, next) => {
console.log('/ middleware');
res.send('<p>The Middleware that handles just /</p>');
});
app.listen(3000);
Parsing Incoming Requests: To parse the request body we can use the body-parser npm package that will gives us the object like data of requested body of data.
Example :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use('/add-product',(req, res, next) => {
// console.log('In the add-product middleware!');
res.send('<form action="/product" method="POST"><input type="text" name="title"><button type="submit">add product</button></form>')
});
app.use('/product',(req , res , next)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req, res, next) => {
// console.log('In another middleware!');
res.send('<h1>Hello message from express js </h1>');
})
//listening to the port
app.listen(3001);
// const server = http.createServer(app)
// //listening to a port for request
// server.listen(3000);
console.log('listening to port 3001');
Limiting Middleware Execution to POST Requests :
Now the above /product middleware will work for both post as well as get request . To limit the /product middle ware for only post request we have to use the express http verbs like : get , post , put , patch or delete.Although these verbs also check the url for exact match.
example :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use('/add-product',(req, res, next) => {
// console.log('In the add-product middleware!');
res.send('<form action="/product" method="POST"><input type="text" name="title"><button type="submit">add product</button></form>')
});
app.post('/product',(req , res , next)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req, res, next) => {
// console.log('In another middleware!');
res.send('<h1>Hello message from express js </h1>');
})
//listening to the port
app.listen(3001);
// const server = http.createServer(app)
// //listening to a port for request
// server.listen(3000);
console.log('listening to port 3001');
Using Express Router :
admin.js :
const express = require('express');
const router = express.Router();
router.get('/add-product',(req, res, next) => {
// console.log('In the add-product middleware!');
res.send('<form action="/product" method="POST"><input type="text" name="title"><button type="submit">add product</button></form>')
});
router.post('/product',(req , res , next)=>{
console.log(req.body);
res.redirect('/');
})
module.exports = router;
shop.js :
const express = require('express');
const router = express.Router();
router.get('/',(req, res, next) => {
// console.log('In another middleware!');
res.send('<h1>Hello message from express js </h1>');
})
module.exports = router;
app.js :
const express = require('express');
const bodyParser = require('body-parser');
const adminRoutes = require('./routes/admin');
const userRoutes = require('./routes/shop');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(adminRoutes);
app.use(userRoutes);
//listening to the port
app.listen(3001);
// const server = http.createServer(app)
// //listening to a port for request
// server.listen(3000);
console.log('listening to port 3001');
Adding a 404 Error Page: Add these line at the bottom of all the routes.
app.use((req , res , next)=>{
res.status(404).send('<h1>Page not found!</h1>');
})
Filtering Paths:
If our routes has some starting point let say /admin/routes then we can configure our routes to reach that routes from app.js file. ANd we can use the same routes for different requests methods.
admin.js :
// /admin/add-product => GET
router.get('/add-product',(req, res, next) => {
// console.log('In the add-product middleware!');
res.send('<form action="/admin/add-product" method="POST"><input type="text" name="title"><button type="submit">add product</button></form>')
});
// /admin/add-product => POSTrouter.post('/add-product',(req , res , next)=>{
console.log(req.body);
res.redirect('/');
})
app.js :
app.use('/admin',adminRoutes);
Using a Helper Function for Navigation:
rootPath.js :
const path = require('path');
module.exports = path.dirname(process.mainModule.filename);
admin.js :
const rootDir = require('../util/rootpath');
const router = express.Router();
router.get('/add-product',(req, res, next) => {
// console.log('In the add-product middleware!');
res.sendFile(path.join(rootDir,'views','add-product.html'));
});
shop.js :
const path = require('path');
const express = require('express');
const rootDir = require('../util/rootpath');
const router = express.Router();
router.get('/',(req, res, next) => {
// console.log('In another middleware!');
// res.send('<h1>Hello message from express js </h1>');
res.sendFile(path.join(rootDir,'views','shop.html'));
})
module.exports = router;
Module summary :
Comments
Post a Comment