How to return after rendering Jade template in Express.JS?
Please consider the simple express.j开发者_开发问答s 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.
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.
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 another res.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 the res.render
.
精彩评论