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

时间:2018-02-24 07:33:44

标签: javascript node.js express routes middleware

我对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页面(检查后是否登录)页面会多次加载,并且不会停止重新加载。 我已经在模板文件夹中定义了login.html页面的所有css,js文件,这些文件是通过引用这个问题加载到中间件之上的 Express middleware getting called many times。这可能是个问题吗?

这可能是什么原因?

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

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

任何猜测?

EDIT1
我仔细研究了这个问题Error: Can't set headers after they are sent to the client,我猜它明确设置标题可能会有问题。

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

EDIT2

有人建议我必须编写一个中间件来检查用户是否经过身份验证,并为此获得一种标志,但正如我上面所述,我正在{{1}中实现逻辑}(客户端)。所以不可能使用它。

2 个答案:

答案 0 :(得分:1)

我有两个猜测:

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

  2. 验证用户登录的中间件应该是这样的(仅适用于您要验证用户的路线)

  3. 中间件应该是这样的

    const isAuthenticated = (req, res, next) => {
        if(req.isAuthenticated()) {
            next();
        } else {
            res.redirect('/');
        }
    }    
    
    app.get('/welcome_page', isAuthenticated, (req, res) => {
      return 'welcome'
    
    });
    

答案 1 :(得分:0)

原因是在/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();
    }
});
相关问题