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
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%"/>
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
).
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With