2016-09-27 43 views
1

我重定向到錯誤的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個文件夾:JSCSS圖片隨機

回答

2

你正在使用項目文件夾進行靜態顯示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');

+0

這是實際的解決方案。我只是將index.html重命名爲main.html,它起作用了! – dll

0

你必須定義根目錄作爲第一個參數提供靜態內容:

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

或者你也可以使用:

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

這不是一個需求,如果你想將例如'/ css/main.css'改爲'/ helloworld/css/main.css',那麼它就是一個虛擬路徑前綴選項。使用('/ helloworld',express.static(__ dirname))'。 – Svenskunganka

2

這是非常重要的,你解決您的目錄結構如果您使用express.static,因爲此時可以運行http://localhost:2222/server.js並下載服務器文件,這是您當前存儲祕密的地方。

我建議你做的是創建一個server/static目錄,並將所有的HTML,CSS,JS,圖片和其他資源裏面,然後改變這一行

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

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

此外,你應該從來沒有,永遠通過GET發送身份驗證數據像你目前使用http://localhost:2222/?username=a&password=b。你需要改變這條路線進入POST請求,通過編輯這一行:

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

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

您可能需要從<form method="get" ...>的HTML來改變你的form<form method="post" ...>

+0

我做了您建議的更改。謝謝:) – dll

相關問題