statemanagement in nodejs | nodejs tutorials

staetemenage storing cooking to identify users 

state management
one client make request with web form
client requested data send to backend
then it will responds
but requested data not tehre
to store taht data
we use statemanagement

we will use different type of module to use statemanagement

sm has two major parts
client side- client side manage management
server side- it is called as servr side management

client side - cookies
serverside - sessions



register teh cookie and remove the cookie using get method api

stored to browser cokokie



i not entered any expiry data
so it will remove automatically whenever browser closed

in below programm set the cookie and remove the cookie


var express = require('express');
var cookieParser = require('cookie-parser');

var app = express();
app.use(cookieParser());

app.get('/',
function (req,res)
{
res.cookie('mycookie', 'tutorials point video tutorials');
res.end('hi there');
}

);

app.get('/remove',
function (req,res)
{
res.clearCookie("mycookie");
res.end('hi there');
}

);

app.listen(8081,
function () {
console.log("server started");
});


encrypt cookie

app.use sesion - secret - encryt, save initialise- if u not do any change in cokokie in their time it will be like original
when login is done - it will false
max age is 60000 milli seconds






var express = require('express');
var cookieParser = require('cookie-parser');
var session= require("express-session");
var morgan = require("morgan");

var app = express();

app.use(morgan('dev'));
app.use(cookieParser());
app.use(session({secret: 'secretkey', saveUnitialised:true, resave: true, cookie: {maxAge: 60000}}));

app.get('/',
function (req,res,next)
{
if(req.session.views)
{
req.session.views++;
res.setHeader('Content-Type','text/html')
res.write('<p> views:' + req.session.views +'</p>')
res.write('<p> expires in:' + (req.session.cookie.maxAge / 1000) +'</p>')
res.end()
}
else {
req.session.views=1
res.end('refresh page')
}
}

);

app.listen(8081,
function () {
console.log("server started");
});


ist prints in browser 
prints 
refresh 
after refresh 
taht count increses


after one idle minute - no refresh - session expires


it will show refresh


 

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...