Tute 08: Middleware, Registration & Log in form and body parser - ariffira/node-basic GitHub Wiki
- Middleware and its use
- get post data from html or view template and capture to the backend express
- handlebars js
- bodyparser, multer middleware
- Create a Registration form and login-form
- is a function()
- take 3 parameters request object, response object, next function
- request(req): a object of HTTP request argument
- response(res): a object of HTTP response argument
- next: a function of Callback argument which end the req-res cycle and call next middleware when you write next()
If you do not have any end of req-res cycle you must call next() to go to next middleware function or it will be hang and loading.......
have a look below:
Add this code which has not middleware just server code for nodejs.
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello Middleware!')
})
app.listen(3000, function() {
console.log("This File running on port 3000")
})
Now we will add our middleware function which will show a message like: "Middleware Activated when server load"
Important: Middleware follows the sequence. It should be before the route '/' otherwise route will not find it. So its like loaded first are also executed first.
Now add this code before your '/' route:
// first middleware to display simple message when load the page
var myLogMessage = function (req, res, next) {
console.log('Middleware Activated when server load!')
next()
}
app.use(myLogMessage)
Check what happens every time you load and how happens.
Now try 2nd middleware after first one. This one will display :
// 2nd middleware to display current time
var currentTime = function (req, res, next) {
req.timeNow = new Date(Date.now()).toLocaleString();
next()
}
app.use(currentTime)
And to check this middleware change res.send() of '/' routes to below code:
var pageContent = 'My Middleware work very fine. It is loaded...!<br>'
pageContent += '<h1>Requested at: ' + req.timeNow + '</h1>'
res.send(pageContent)
Thats just basic of middleware and its usage. We already used it before in router examples. Now try some third party middleware and use them inside your code.
List of express Third party middleware
Body-parser:
- capture data coming via a form
- install: npm install --save body-parser
Now lets see how could we capture post data from html form. Its very simple and easy with body-parser.
Step 01: create your package.json file and add express, body-parser, start scripts etc like below:
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "*",
"body-parser": "*"
},
npm init
npm install
Step 02: create app.js file and put below code
// app.js server code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// urlencoded for form data, parsing application/x-www-form-urlencoded
// if extended true any data can post, if false nested object can not post
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (request, response) => response.sendFile(`${__dirname}/index.html`));
app.post('/api/register', (request, response) => {
const postData = request.body;
console.log(postData);
response.send('Successfully received your Data! Thanks');
});
app.listen(3000, () => console.info('Application running on port 3000'));
Step 03: create index.html and add these values
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Express POST data Tute</title>
</head>
<body>
<form action="/api/register" method="POST">
First Name: <input type="text" name="firstName" id="firstName">
<button type="submit">Submit data</button>
</form>
</body>
</html>
Now go to localhost:5000/ and input your firstname and see the terminal console in your ide. You should see the data as object there. and success message in browser.
Try add more and create real form and test.
<form action="/api/register" method="POST">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName">
Email: <input type="email" name="email">
<button type="submit">Submit data</button>
</form>
Lets use template engine "handlebarjs" and setup things like below code:
const path = require("path")
// include express handlebar module
const exphbs = require('express-handlebars');
// This is config for render view in `views` folder
// and use handlebars as template engine here
app.set('views', path.join(__dirname, 'views'))
// setting default page layouts which is under views/layouts/index.handlebars and view engine as handlebarjs
app.engine('handlebars', exphbs({defaultLayout: 'index'}));
app.set('view engine', 'handlebars')
Lets use bootstrap inside index.handlebars file which is default layout in: views/layouts/index.handlebars
Here {{{body}}} will show content for different routes but index file will be fixed and that will make single page application. Create more routes in app.js and more view file like signin, home, register etc.
App.js looks like that now:
// initial page route
app.get('/', (req, res) => {
res.render('registration') // render registration form
});
// registration form post route
app.post('/register', (req, res) => {
const postData = req.body;
console.log(postData);
res.redirect('/signin');
});
// signin page route
app.get('/signin', (req, res) => {
res.render('signin') // render signin form
});
// post signin data routes
app.post('/signin', (req, res)=> {
const postData = req.body;
console.log(postData);
res.redirect('/home');
});
// homepage routes after login
app.get('/home', (req, res)=> {
res.render('home')
});
Please check the code in git tute08
Now Create a nice form inside register.handlebars which will have registration form.
install local storage: npm install node-localstorage
add this:
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./userData'); // userData will keep your user
Then inside app.post('/register') update code like below:
// post registration form route
app.post('/register', (req, res) => {
const postData = req.body;
console.log(postData);
localStorage.setItem('user', JSON.stringify(postData));
res.redirect('/signin');
});
Also update signin post route:
// post signin data routes
app.post('/signin', (req, res)=> {
let postData = req.body;
console.log(postData.email);
// get data from local storage
let userFromStore = JSON.parse(localStorage.getItem('user'));
console.log(userFromStore.email);
// check user access
if (postData.email == userFromStore.email) {
res.redirect('/home');
} else {
console.log('Wrong email! Please give right one')
res.redirect('/signin');
}
});
Test for others