2017-04-22 74 views
1

我是比較新的網絡開發和我試圖建立一個基本的身份驗證。它適用於非靜態路徑,但是我無法理解靜態路徑如何工作。我最近發現,當我使用靜態路徑.../home.html請求身份驗證頁面(/ home)時,無論如何它都會提供路徑。我已經嘗試以認證/ home的方式對其進行身份驗證,但是它不起作用,儘管我從控制檯日誌中看到身份驗證失敗,所以isAuthenticated被調用。身份驗證靜態路徑,表達的NodeJS護照HTML

,我將不勝感激,如果有人可以點我到正確的方向,因爲我想了解,纔能有一個正確的身份驗證詢問/家,/home.html之間的差異。我還注意到,當我瀏覽他們時,我訪問的大多數網站都沒有任何靜態路徑。因爲只有我知道如何從按鈕重定向頁面的方式是使用href =/path.html,所以我也在第一次按鈕點擊後提供靜態路徑。這將是很好的知道如何提供一個非靜態路徑(href = /路徑不工作,如果我不添加.html在最後)

可能的答案是相當直接,但我不知道哪些字我應該看看和我的最佳知識,我也無法找到這個在stackoverflow。所以請幫助我這個noob問題。

這裏是我設置的中間件:

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()); 
app.use(cookieParser()); 
app.use(express.static('public')); 
app.set('views', __dirname + '/public'); 
app.engine('html', engines.mustache); 
app.set('view engine', 'html'); 

app.use(require('express-session')({ 
    secret: 'so secret much safety', 
    resave: true, 
    saveUninitialized: true 
})); 
app.use(passport.initialize()); 
app.use(passport.session()); 

這裏是我嘗試驗證:

function isAuthenticated(request, response, next) { 
    console.log('isauthenticated:'+request.isAuthenticated()); 
    if (request.isAuthenticated()){return next();} 
    else{response.redirect('/');} 
} 


app.use('/home', isAuthenticated, function(request, response){ 
    response.render('home.html'); 
    //response.send('if you are viewing this page it means you are logged in'); 
}); 

app.use(express.static(__dirname + '/home'), isAuthenticated, function(request, response){ 
    //should serve the page here 
}); 
+0

你有你的觀點公開的文件夾中,所以沒有驚喜,你可以訪問他們*「無論什麼」 *。將您的意見移到公共文件夾之外,您將不再能夠使用像/home.html這樣的鏈接訪問它們。我強烈建議您閱讀關於表達作品的一些基本教程! – Molda

回答

0

,當我試圖從公用文件夾移開享有的NodeJS無法找到他們雖然,雖然我改變了查看目錄。然後我發現從應用程序切換到路由器完全解決了這個問題。這可能相當微不足道,但花了我一些時間來解決我的問題。如果另一個業餘有同樣的問題,在這裏結束,以下爲我工作:

var router  = express.Router(); 
... 
app.set('views', __dirname + '/views'); 
... 
router.use('/home', isAuthenticated, function(request, response){ 
    response.render('home'); 
}); 

router.use(express.static(__dirname + '/home'), isAuthenticated, function(request, response){ 
    console.log('it works'); 
});