node.js - 如何从路由器调用app.js中的express 4.0中间件函数?

标签 node.js express middleware

我有一个中间件函数来执行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();
}

如果您在其他文件中有路由,则可以传递 approuter

external.js

module.exports = function(router) {

}

关于node.js - 如何从路由器调用app.js中的express 4.0中间件函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25385185/

相关文章:

node.js - 将 'this' 传递给构造函数中的类变量

javascript - 我应该什么时候开始和结束我的node.js SQL 连接?我应该从一开始就使用池化吗?

go - 如何在 Gin 中间件中获取 url?

c# - ASP.NET Core 中的中间件是如何执行的

java - 无法停止ActiveMQ Producer?

javascript - 使用现有的全局变量在 Node.js 中执行命令行参数?

javascript - 使用 API 和 Mongoose 的 AngularJS SPA

javascript - 如何将 express.js 服务器部署到 Netlify

node.js - 在 Sequelize 中保存 JSON 对象

forms - Node Express 3.4.4 和 Jade 表单数据未定义