I am trying to write a code for redirecting all my Http
requests to Https
, now I wanted to ask I have seen below code on many different websites but some of them use return
with res.redirect
, some use return
after
res.redirect
, some don't use anything and some use only next()
after
res.redirect
.
I just want to ask what is the use of return
or calling next()
here. Or am I missing anything here ??
app.use(function(req,res,next) {
if(req.headers["x-forwarded-proto"] == "http") {
console.log('Request was HTTP');
/* return ??*/ res.redirect("https://" + req.headers.host + req.url);
// return or next() or nothing ??.
} else {
console.log('Request was not HTTP');
return next();
}
});
next()
is a part of Express middleware. It tells to execute the next middleware function on the functions flowchart. If its not used the next middleware will not be executed.
return
is used just to ensure that the execution stops after triggering the callback i.e no part of callback is processed again whether you use it with next
or redirect
it has same use to stop the execution of that particular function.