如何使Express中间件子堆栈保持连接到特定路由?
我的应用程序中有一个子站点,该站点允许编辑和提供一些JSON。编辑器用作static
资源,并且有GET
和POST
数据路由,由编辑器和外部使用者使用。
因为我只希望管理员修改数据,但每个人都可以查看,所以我想保护'/'和POST路由,但不保护GET路由。为此,我希望在每个路由规范中使用middleware子堆栈是正确的解决方案。因此,有一个通用的auth.js
文件,其导出函数专门包含在2条安全路由中,但在GET中省略。
问题是,当我将安全的“ /”路由的代码放在免费的所有GET路由的代码上方时,我遇到了GET路由的身份验证挑战!现在,我知道通常app.use
中间件将按定义的顺序工作,但我的想法是仅使用特定于路由的子堆栈用于该路由。
这可能会说明一件事:Express在解析请求路径时是否开始调用中间件?我的意思是,如果我有一个路由/jfile/jones/tamari/
,它将调用/
路由处理程序,然后是/jfile
路由处理程序,然后是/jfile/jones
路由处理程序,然后是/jfile/jones/tamari
路由处理程序?它不应该完全匹配路由,而不是逐位匹配,而仅针对任何请求调用最特定的处理程序吗?
简单的解决方法是:“只需将经过身份验证的路由之后设置为自由路由”-是的,可行,但是为什么?为什么子堆栈中间件泄漏到其他路由?以后还会引起什么其他问题?
这里是一些代码:
auth.js
const pass ='Basic WW91IGFyZSBzbyBuYXVnaHR5IQ==';
module.exports.isAuth = function(req, res, next) {
if ( req.headers.authorization !== pass ) {
res.status(401).send('Unauthorized');
} else {
next();
}
}
jfile.js
const fs = require('fs');
const path = require('path');
const busboy = require('connect-busboy');
const auth = require('./auth.js');
const dataFolder = './data';
const webPath = '/jfile';
app.use(busboy()); // handles POST data
function setNoCache(res, path) {
res.setHeader('Cache-Control', 'max-age=0');
res.setHeader('Expires', 0);
}
const fname = 'jason.json';
app.use('/', auth.isAuthorized, static('./public',
{ cacheControl: true, setHeaders: setNoCache })
);
app.get(webPath, function (req, res) {
var download = false;
if (typeof req.query.download != 'undefined') {
download = true;
}
var file = path.join(dataFolder, fname);
setNoCache(res);
// Since this route deals only with 1 type of file, we set a static public name for it
// This also masks the date part of our manual version control system. :-\
if (download) {
res.setHeader('Content-Disposition',`Attachment;filename=${fname}`);
}
res.type('json');
try {
var stream = fs.createReadStream(file);
stream.pipe(res);
} catch (err) {
res.status(500).send(JSON.stringify(err));
return;
}
});
app.post(webPath, auth.isAuthorized, function (req, res) {
var newFileName = futil.newFileIn(dataFolder);
if(!req.busboy) {
res.status(500).send('Missing library');
return;
}
req.busboy.on('file', function (field, file, filename) {
file.pipe(fs.createWriteStream(filename));
});
busboy.on('finish', function() {
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
});
回答如下:如果我有路线
/jfile/jones/tamari/
,它将呼叫/
路由处理程序?
是,因为app.use('/', ...)
匹配所有记号。
如果使用app.use('/jfile', ...)
,将调用以/jfile
开头的所有请求的中间件
仅在要防止未经授权的访问的溃败中使用中间件
示例
[app.get(path, yourMiddleware, callBack)
仅此溃败将使用中间件
代码示例
auth.js
module.exports = function(req, res, next) {
if (req.headers.token) {
// verification of token
next();
} else {
res.send({ status: 401, message: "Unauthorized" });
}
};
index.js
const auth = require("./middleware/auth");
app.get("/", auth, function(req, res) {
res.send({ status: 200, message: "With auth" });
});
app.post("/jfile", auth, function(req, res) {
res.send({ status: 200, message: "With auth" });
});
app.get("/jfile", function(req, res) {
res.send({ status: 200, message: "Without auth" });
});