How to print cookie in .ejs view engine

六眼飞鱼酱① 提交于 2021-02-07 12:47:23

问题


How do I print cookie value in form attribute?

Here is the code I have so far.

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 check My Cookie in console cookie is set

document.cookie :

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


回答1:


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%"/>



回答2:


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).




回答3:


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); }


来源:https://stackoverflow.com/questions/49043817/how-to-print-cookie-in-ejs-view-engine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!