app.get() 被调用多次表示

app.get() being called multiple times express

我是 node.js 的新手,正在尝试制作一个简单的网站,该网站首先要求进行身份验证,然后将用户重定向到一个页面。

所以,我所做的是创建一个中间件,它会监听对我的网站发出的每个请求。

这个中间件的作用是检查用户是否登录我的网站,如果是,则重定向到请求的页面,如果没有,则重定向到登录页面,这是我的代码。

var express = require('express');
var app = express();

// middleware for using static files 
app.use('/public', express.static(__dirname + '/public')); // all the js files for check_before.html
app.use('/templates', express.static(__dirname + '/templates')); // here are css/js files for login.html 

// setting up views folder
app.set('views', __dirname + '/views'); // check_before.html is sitting here
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use((req, res, next) => {
    res.render('check_before.html'); 
// here in the html I implement the logic using js files which are located in public folder.

    next();

});

// if not logged in , the user gets here
app.get('/login', (req, res, next) => {

    res.render('login.html')

});

// if logged in redirect to some page 
app.get('/welcome_page', (req, res) => {
    return 'welcome'

});

一切顺利,直到用户点击 http://localhost:8000/login 页面(在检查他们是否登录后),该页面持续加载多次并且不会停止重新加载。 我已经通过reffereing to this question在中间件上方加载的模板文件夹中定义了所有css,login.html页面的js文件 。这会是个问题吗?

这可能是什么原因?

这是我在控制台中遇到的错误。

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

有什么猜测吗?

编辑1
我经历了这个问题 Error: Can't set headers after they are sent to the client ,我想它的结论是明确设置 headers 可能会有问题。

这会是一个原因吗?因为在我的逻辑中,如果用户未登录,我只是使用 window.location.replace('http://localhost:8000/login') 将用户重定向到 login 页面。 我应该使用任何其他方法进行重定向吗?

编辑2

有人建议我必须编写一个中间件来检查用户是否经过身份验证,并为此获得某种标志,但正如我上面所说,我正在 check_before.html(客户端)。所以将无法使用它。

我有两个猜测:

  1. 您不应该在 res.render 之后调用发送(或任何其他函数)。

  2. 验证用户登录的中间件应该是这样的(只适用于你想验证用户的路由)

中间件应该是这样的

const isAuthenticated = (req, res, next) => {
    if(req.isAuthenticated()) {
        next();
    } else {
        res.redirect('/');
    }
}    

app.get('/welcome_page', isAuthenticated, (req, res) => {
  return 'welcome'

});

原因是在您的 /login 请求之前调用了中间件。要修复它,您需要修改中间件功能。它应该是这样的:

app.use((req, res, next) => {
    if(isLoggedIn) {  //isLoggedIn is a flag that checks whetehr user is logged-in or not
        res.render('check_before.html');
    } else {
        // here in the html I implement the logic using js files which are located in public folder.

        next();
    }
});