Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print cookie in .ejs view engine

How May I print cookies value in the form attribute?

This is the code that I am trying.

if(req.body.remember_me){
    res.cookie("cookie_email_id", req.body.email);
    res.cookie('password', req.body.password);
}else{
    res.clearCookie("cookie_email_id");
    res.clearCookie("password");
}

and I have checked cookie in console and cookie is stored there please see document.cookie :

cookie_email_id=abc%40gmail.com; password=123456789

like image 394
Shubham Azad Avatar asked Mar 01 '18 06:03

Shubham Azad


3 Answers

To pre-fill form inputs through ejs, first of all you need to set the cookies via res.cookie() .To autofill these values in a form field .You need to get the cookies from the request and assign it to your render method.

For this you can use cookie-parser middleware like this and get the cookie values in req.cookies/req.signedCookies.

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

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

app.get('/', function (req, res) {
  // Cookies that have not been signed
  console.log('Cookies: ', req.cookies)

  // Cookies that have been signed
  console.log('Signed Cookies: ', req.signedCookies)
})

app.listen(8080)

From the route you can call your ejs render method with all the properties to autofill

something like

res.render('user_profile',{name:req.cookies.name, age:req.cookies.age})

You can then place the values in your ejs form fields as like

<input type="text" id="name" value="%name%"/>
<input type="text" id="age" value="%age%"/>
like image 150
jenil christo Avatar answered Oct 19 '22 05:10

jenil christo


When you response , try this:

res.render("your_page", {email: req.body.email, password: req.body.password});

And set email and password to value of input (with ejs).

like image 27
hong4rc Avatar answered Oct 19 '22 07:10

hong4rc


Cookies can be retrieved from req.headers.cookie and the same can be passed to EJS template or anywhere else based on requirement.

For Example :

Print cookie in console:

router.get("/example"), (req, res) => { console.log(req.headers.cookie); }
like image 21
Selvam Raju Avatar answered Oct 19 '22 05:10

Selvam Raju