我有一个中间件函数来执行app.js(入门JavaScript)中的基本授权。但是其他javascript文件中还有一些路由器文件。我的问题是如何调用路由器中的授权中间件功能?
这是我的 app.js:
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
module.exports = app;
我的路由器文件index.js:
var express = require('express');
var router = express.Router();
router.get('/', auth, function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
显然这里没有定义身份验证。谁能告诉我如何在我的 index.js 路由器功能中使用 auth 中间件功能?谢谢
最佳答案
我不确定您到底想用什么导出。
module.exports = app;
在 app.js 中
这是一个简化的解决方案:
index.js
var express = require('express');
var app = express();
var auth = require('./auth');
var router = express.Router();
router.use(auth); // Auth middleware is first
router.get('/', function(req, res) {
return res.send('Hello world');
}
// More routes can go here
// require('./external')(router);
// router.get('/route', function(req, res) {}
app.use(router);
app.listen(3000);
auth.js
module.exports = function(req, res, next) {
return next();
}
如果您在其他文件中有路由,则可以传递 app
或 router
external.js
module.exports = function(router) {
}
关于node.js - 如何从路由器调用app.js中的express 4.0中间件函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385185/