[英]Show flash message from server.js to html in particular div with id
I get an error message from server.js and it gets display using 'connect-flash' but it gets redirected with blank page. 我从server.js收到一条错误消息,并使用“ connect-flash”显示了该消息,但重定向到了空白页面。 I want to show the message on same page in a specific div with id in html. 我想在HTML中ID为ID的特定div中的同一页上显示该消息。 Here is my server.js code 这是我的server.js代码
app.get('/', function (req, res) {
// var username = req.body.
if (global.debugMode) debugger;
console.log("userLogin.html".grey);
var loginmsg = req.flash('error');
if(loginmsg.length>0){
console.log(loginmsg);
res.send('<h3>'+loginmsg+'</h3>');
}
res.sendFile(`${path.dirname(__dirname)}//public/Login/userLogin.html`);
});
I want to show 'loginmsg' in specific div on same page but it disaplay on blank page 我想在同一页面的特定div中显示“ loginmsg”,但在空白页面上却不显示
Your problem comme from express understanding i think. 我认为您的问题来自表达的理解。 You get a blank page with your flash message in a <h3>
? 您会在<h3>
得到空白页面,其中包含Flash消息? It's because you do a res.send
when you have a flash message. 这是因为当您res.send
Flash消息时会重新发送。 We can only send one response for one request ( https://www.webnots.com/what-is-http/ ), or here you try to send first the h3
then send your html file. 对于一个请求,我们只能发送一个响应( https://www.webnots.com/what-is-http/ ),或者在这里您尝试先发送h3
然后发送html文件。 It's not the good way to do such things. 这不是做这些事情的好方法。
With your solution, the only way to do what you whant is to build the html string dynamically : 对于您的解决方案,您想要做的唯一方法是动态构建html字符串:
var myHtml = `<html><head>...</head><body>`
if(loginmsg.length > 0) { myHtml += `<h3>${loginmsg}</h3>` }
myHtml += `rest of my page ...`
myHtml += `</body></html>`
res.send(myHtml)
But it's clearly no the good practice to do this. 但这显然不是一个好习惯。
Use templates ! 使用模板! ( http://expressjs.com/en/guide/using-template-engines.html ). ( http://expressjs.com/en/guide/using-template-engines.html )。 With template you can build an html page with dynamic values in it, like your flash message ! 使用模板,您可以构建一个包含动态值的html页面,例如Flash消息! With ejs template ( https://www.npmjs.com/package/ejs ) you will have a .ejs
file template like that : 使用ejs模板( https://www.npmjs.com/package/ejs ),您将拥有一个.ejs
文件模板,如下所示:
<html>
<head>...</head>
<body>
<% if (loginmsg) { %>
<h3><%= loginmsg %></h3>
<% } %>
Rest of my page...
</body>
</html>
And in your express app : 在您的快速应用中:
app.get('/', function (req, res) {
var loginmsg = req.flash('error');
...
res.render('myTemplate', { loginmsg });
});
Have fun ✌️ 玩得开心✌️
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.