sessionandcookienodejs

 mongoose.model(collectionname,scema);


session:--

express-session install


let session=require("express-session");


app.use(session({

resave:false,//if the session value doesnt save then does'nt save again

saveUninitialized:false,//if the client doesnt have give the uninilized data then doesnt save

secret:"key1"//secret key

});


router.get("/",function(req,res){

req.session.key1='hello';//value[true]

res.render("index");//index ejs page..

})

//u can access that session in other routes:---

router.get("/",function(req,res){

req.session.key1='hello';//value[true]

res.render("index");//index ejs page..

})

router.get("/check",function(req,res){


console.log(req.session.key1);

//or u can check:--

if(req.session.key1){


}

else{

 

}


}

router.get("/check",function(req,res){

req.session.destroy(function(err){

if (err) throw err;

res.send('session removed");


}


cookie:--

npm i cookieParser[express generator]

let cookieParser=require("cookie-parser");

app.use(cookieParser());


router.get("/",function(req,res){

res.cookie("age",25);//name//value...

res.render("index");

}


router.get("/read",function(req,res){

console.log(req.cookies.age);

res.send("check");

});


router.get("/del",function(req,res){

res.clearCookie("age");

res.send('clear');

});




Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation