如何在.ejs视图引擎中打印cookie [英] How to print cookie in .ejs view engine
问题描述
如何在表单属性中打印cookie值?
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");
}
我已经检查了控制台Cookie中的我的Cookie"是否已设置
And I have check My Cookie in console cookie is set
document.cookie
:
cookie_email_id = abc%40gmail.com;密码= 123456789
推荐答案
要通过ejs预填充表单输入,首先需要通过res.cookie()设置cookie.要在表单字段中自动填充这些值.您需要从请求中获取Cookie并将其分配给您的render方法.
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.
为此,您可以使用这样的cookie解析器中间件,并在req.cookies/req.signedCookies中获取cookie值.
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)
从路由中,您可以调用具有所有要自动填充的属性的ejs渲染方法
From the route you can call your ejs render method with all the properties to autofill
类似
res.render('user_profile',{name:req.cookies.name, age:req.cookies.age})
然后您可以将值放置在ejs表单字段中,例如
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%"/>
这篇关于如何在.ejs视图引擎中打印cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!