我重定向到錯誤的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