当express.static(__ dirname)函数在node.js中使用express时,redirect到错误的html页面

我有一个名为login.html的login页面和一个名为index.html的索引页面。 我想进行身份validation,只有一个连接的用户可以访问索引页面。

我没有在loginHTML页面上实现post方法。 我必须通过以下url手动发送login用户名和密码:

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

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

 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个文件夹: JSCSS图像随机

你正在使用项目文件夹静态,因为你发布app.use(express.static(__dirname)); 。 ExpressJS使用index.html作为默认索引页面。 所以你需要将index.html重命名为main.html类的东西,并使用res.sendfile('main.html');

备用解决scheme:

创build一个文件夹说public并把所有的静态内容(js,css和图像)到public文件夹,请不要把HTML文件放入public文件夹,并使用app.use(express.static(__dirname) + '/public');

如果使用express.static ,修复目录结构非常重要,因为此时可以运行http://localhost:2222/server.js并下载服务器文件,这是您的位置目前存储你的秘密。

我build议你做的是创build一个server/static目录,并放置所有的HTML,CSS,JS,图像和其他资产,然后改变这一行

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

 app.use(express.static(__dirname + '/static')); 

此外,你永远不应该通过GET参数发送auth数据,就像你现在使用http://localhost:2222/?username=a&password=b 。 您需要通过编辑以下行来将此路由更改为POST请求:

 app.get("/login", function(req, res) { 

 app.post("/login", function(req, res) { 

您可能需要将HTML中的表单从<form method="get" ...>更改为<form method="post" ...>

您必须将根目录定义为用于提供静态内容的第一个参数:

 app.use('/', express.static(__dirname)); 

或者您也可以使用:

 app.use(express.static(__dirname + '/'));