我重定向到错误的html页面有一个名为login.html的一个登录页面,并呼吁index.html的索引页。我想进行身份验证,只有连接的用户才能访问索引页面。在node.js中使用express.static(__目录名)功能时用快递
我没有在登录HTML页面上实现post方法。我通过这个网址去手动发送的登录用户名和密码:
http://localhost:2222/?username=a&password=b
一切工作,但我看不到我的CSS,JS和index.html的一些其他文件。为了解决这个问题,我说这在我的代码开头:
app.use(express.static(__dirname));
的问题是,现在如果我去本地主机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是一个名为服务器文件夹中。在此文件夹服务器也是4个文件夹:JS,CSS,图片和随机。
这是实际的解决方案。我只是将index.html重命名为main.html,它起作用了! – dll