gpt4 book ai didi

javascript - 在带有 express 的 node.js 中使用 express.static(__dirname) 函数时重定向到错误的 html 页面

转载 作者:行者123 更新时间:2023-11-30 09:44:04 26 4
gpt4 key购买 nike

我有一个名为 login.html 的登录页面和一个名为 index.html 的索引页面。我想进行身份验证,并且只有连接的用户才能访问索引页面。

我没有在登录 HTML 页面上实现 post 方法。我必须通过以下网址手动发送登录用户名和密码:

http://localhost:2222/?username=a&password=b

一切正常,但我在 index.html 中看不到我的 css、js 和其他一些文件。为了解决这个问题,我在代码的开头添加了这个:

app.use(express.static(__dirname)); 

问题是现在如果我转到 localhost:2222,它会显示 index.html 文件而不是 login.html 文件。即使我使用:

app.get('/', function (req, res) {
res.redirect('/login');
});

它是怎么来的?我该如何解决这个问题?

完整代码为:

var express = require("express");
var port = process.env.PORT || 2222;
var app = express();
app.use(express.static(__dirname));
var session = require('express-session')
app.use(session({
secret: 'keyboardcat',
resave: true,
saveUninitialized: true
}));

function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.sendfile('login.html');
} else {
next();
}
}
app.get('/', function (req, res) {
res.redirect('/login');
});
app.get("/login", function(req, res) {
if (req.query.username === 'a' && req.query.password === 'b') {
req.session.user_id = req.query.username;
res.redirect('index');
} else {
res.sendfile('login.html');
}
});
app.get('/index', checkAuth, function(req, res){
res.sendfile('index.html');
});

app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});

我的文件树如下:index.html、login.html 和 server.js 位于名为server 的文件夹中。在此文件夹服务器中还有 4 个文件夹:JSCSSImagesRandom

最佳答案

在发布 app.use(express.static(__dirname)); 时,您使用的是静态项目文件夹。 ExpressJS 使用 index.html 作为默认索引页。因此,您需要将 index.html 重命名为 main.html 之类的名称并使用 res.sendfile('main.html');

替代解决方案:

创建一个文件夹public 并将所有静态内容(js、css 和图像)放入public 文件夹,请不要将html 文件放入public 文件夹 并使用 app.use(express.static(__dirname) + '/public');

关于javascript - 在带有 express 的 node.js 中使用 express.static(__dirname) 函数时重定向到错误的 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719693/

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