[英]How to direct to default landing page with basic-auth middleware in Express
我正在嘗試向Express上的整個網站添加基本授權。 如果用戶輸入正確的憑據,那么我希望顯示標准登錄頁面。 如果不是,則應將用戶帶到“拒絕訪問”頁面。 我試圖弄清楚如何更改basic-auth中間件示例來實現此目的:
var http = require('http')
var auth = require('basic-auth')
// Create server
var server = http.createServer(function (req, res) {
var credentials = auth(req)
if (!credentials || credentials.name !== 'john' || credentials.pass !== 'secret') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="example"')
res.end('Access denied')
} else {
res.end('Access granted')
}
})
如果我使用next();
而不是res.end()
,我得到一個undefined
錯誤。
var server = http.createServer(function (req, res, next) {
var credentials = auth(req)
if (!credentials || credentials.name !== 'john' || credentials.pass !== 'secret') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="example"')
res.end('Access denied')
} else {
next();
}
})
這是我的路線:
app.use('/api/things', require('./api/thing'));
// . . .
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
next
是connect
的構造,這是Express Web服務器下面的中間件庫。 但是,您正在將自己的處理函數傳遞給http服務器。 您應該使http服務器使用express應用程序來處理請求。 然后,express的中間件使其變得簡單。
var http = require('http');
var auth = require('basic-auth');
var app = require('express')();
var server = http.Server(app);
server.listen(3000);
app.get('/', ensureCredentials, function(req, res){
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
})
app.all('*', function(req, res){
res.redirect('/');
})
function ensureCredentials(req, res, next){
// do logic
if(){
res.status(403).send('Unauthorized')
} else {
next();
}
}
重要的是要理解,在使用res.send(), res.json(), res.end(), res.redirect()
發送響應后,Express不會執行任何中間件。 因此,在一種情況下( /
驗證失敗), ensureCredentials
函數將發送403,並且app.get('/')
處理函數將不會運行。 在另一種情況下,auth簽出,調用next()
,然后運行app.get('/')
處理函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.