Express.JS中渲染Jade模板后如何返回?
请考虑简单的express.js 路由:
app.get("/test", function(req, res) {
if(condition1) {
res.render("foo", {
title : "Test"
});
}
console.log("HERE");
if(condition2) {
res.render("bar", {
title : "Test2"
});
}
});
现在,在这个人为的示例中,有时条件1 为真,有时条件2 为真。但是,在条件 1 为 true 的情况下,控件会通过并打印出 console.log 行,然后在遇到其他渲染时失败:
错误:发送后无法设置标头。
就像需要结束响应什么的,但我已经尝试过,但无济于事。任何帮助将不胜感激。谢谢。
Please consider the simple express.js route:
app.get("/test", function(req, res) {
if(condition1) {
res.render("foo", {
title : "Test"
});
}
console.log("HERE");
if(condition2) {
res.render("bar", {
title : "Test2"
});
}
});
Now, in this contrived example, sometimes condition1 will be true, and other times, condition2. However, in the case that condition1 is true, the control passes through and prints out the console.log line and then fails when it hits the other render with:
Error: Can't set headers after they are sent.
It's like the response needs to be ended or something, but I've tried that, to no avail. Any help would be appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我只是使用
return res.render()
。当你说它不起作用时,这很奇怪,因为 return 实际上应该阻止函数的其余部分执行。
I just use
return res.render()
.It's strange when you say it doesn't work, because return really should stop the rest of the function from executing.
只需使用
else
,这样就只有一个代码路径通向 res.res.send
已结束响应,但您正尝试使用另一个res.render
发送另一个响应只需将第二个 if 更改为
else if
,并移动代码以实现此目的,即将 console.log 移至所有条件之上。或者,我相信您可以在
res.render
之后放置一个return
语句。Simply use an
else
, so that only one code path leads to a res.res.send
already ends a response, but you are trying to send another response with anotherres.render
Simple change the second if to an
else if
, and move around the code to allow for this, ie move the console.log above all the conditionals.Or, I believe you can just place a
return
statement after theres.render
.