gpt4 book ai didi

javascript - app.get() 被多次调用 Express

转载 作者:行者123 更新时间:2023-12-03 02:25:44 25 4
gpt4 key购买 nike

我对 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页面(在检查他们是否登录后)页面不断加载多次并且获胜不要停止重新加载。我已经在 templates 文件夹中定义了 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

有什么猜测吗?

编辑1
我经历过这个问题Error: Can't set headers after they are sent to the client ,我猜它的结论是显式设置 header 可能会出现问题。

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

编辑2

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

最佳答案

我有两个猜测:

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

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

中间件应该是这样的

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

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

});

关于javascript - app.get() 被多次调用 Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com