Filtering paths and creating html page in express.js

We added express router to handle routes. One single router file handles multiple routes.

Adding a path for router in App.js 

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use('/test',route);
app.use((req, res,next)=>{
   res.status(404).send('

Page not found

'); }); const server = http.createServer(app); server.listen(3000);

In router middleware we used path −/p>

app.use('/test',route);

Router will handle all paths starting with /test e.g. /test/add-username

We have to change action in form in routes.js file −

router.get('/add-username', (req, res,next)=>{
   res.send('
   
'); });

Routes.js file −

const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
   res.send('
   
'); }); router.post('/post-username', (req, res, next)=>{    console.log('data: ', req.body.username);    res.send('

'+req.body.username+'

'); }); module.exports = router;

This mechanism of adding filtering for router helps in putting common urls handler in one section.

Creating html5 page in vs code editor

Create a new folder for storing html pages , let’s say views folder. Create a new file add-user.html.

In add-user.html file, if we type html and hit ctrl + space we will get an options for creating a default skeleton for html5. Select it and we will have below html5 page −


   
      
      
      Document
   


We can copy the form from route.js file here in html body.


Updated on: 2020-05-13T13:32:50+05:30

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements