最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

调用res.redirect后使用return或next

IT培训 admin 2浏览 0评论

调用res.redirect后使用return或next

我正在尝试编写一个代码,用于将我所有的Http请求重定向到Https,现在我想问我在许多不同的网站上看到下面的代码,但其中一些使用returnres.redirect,一些使用return after res.redirect,一些不使用任何东西和一些只使用next() after res.redirect

我只是想问一下return的用法是什么,或者在这里调用next()。或者我在这里遗漏了什么?

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()是Express中间件的一部分。它告诉在函数流程图上执行下一个中间件函数。如果未使用,则不会执行下一个中间件。

return仅用于确保在触发回调后执行停止,即无论是否使用nextredirect,它都不会再次处理回调的一部分,它具有相同的用途来停止执行该特定函数。

调用res.redirect后使用return或next

我正在尝试编写一个代码,用于将我所有的Http请求重定向到Https,现在我想问我在许多不同的网站上看到下面的代码,但其中一些使用returnres.redirect,一些使用return after res.redirect,一些不使用任何东西和一些只使用next() after res.redirect

我只是想问一下return的用法是什么,或者在这里调用next()。或者我在这里遗漏了什么?

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()是Express中间件的一部分。它告诉在函数流程图上执行下一个中间件函数。如果未使用,则不会执行下一个中间件。

return仅用于确保在触发回调后执行停止,即无论是否使用nextredirect,它都不会再次处理回调的一部分,它具有相同的用途来停止执行该特定函数。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论