Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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('<h1> Page not found </h1>');
});
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('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
Routes.js file −
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>');
});
router.post('/post-username', (req, res, next)=>{
console.log('data: ', req.body.username);
res.send('<h1>'+req.body.username+'</h1>');
});
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 −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html>
We can copy the form from route.js file here in html body.
<form action="/test/post-username" method="POST"> <input type="text" name="username"> <button type="submit"> Send </button> </form>
