使用express.js和locomotive.js在中间件中添加api标记

我正在构build一个restapi服务器,我将使用一个angularjs前端。 我正试图实现一些运行在每个请求上的中间件。 对于每一个请求,我想检查一个API标记,如果存在继续检查是否有效,如果不存在,则返回未经授权的响应,而不完成请求。

这些请求在我尝试添加中间件之前就工作了,但是一旦我尝试添加中间件或在主要路由超时之前赶上路由,

http://localhost:3000/developer/test?api=fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f { response: { id: "test", api: "fhgjtyd6fjrj4off6r4rhgjdldksrghiue750f" } } 

这两个路线都可以工作,但我更喜欢资源版本。 ( http://locomotivejs.org/guide/routing/ )

 this.match('/developer', { controller: 'developer', action: 'show' }); this.resources('developer'); 

这是我一直在试图遵循的一个例子,因为它看起来大部分是我需要做的。 ( http://webapplog.com/intro-to-express-js-parameters-error-handling-and-other-middleware/ ),但目前我试图实现这样的东西,它超时的路线。 它将console.log()方法中的东西,但它的行为就像它正在等待它永远不会得到的东西。 如果我尝试使用下一个()我得到一个未定义的错误,我不想将该应用程序注入到身份validation器或任何其他对象。

 function requiredParamHandler(param){ //do something with a param, eg, check that it's present in a query string return function (req,res, next) { //use param, eg, if token is valid proceed with next(); next(); }); } app.get('/api/v1/stories/:id', requiredParamHandler('token'), story.show); var story = { show: function (req, res, next) { //do some logic, eg, restrict fields to output return res.send(); } } 

我开始构build一个Auth模块,该模块将使用该模块来检查和validationapi标记。

 var Authenticator = function () { this.requireApiToken = function() { console.log('requireApiToken'); } }; module.exports = Authenticator; 

我试图按照明确的说法在他们的api参考文档中做

 app.all(path, [callback...], callback) app.all('/api/*', requireAuthentication); 

我在locomotives config / environments / all.js里面添加了上面这行

 auth = new Authenticator(); this.express.all('*', auth.requireApiToken); 

但是,这是路线开始超时的时候,我什至没有得到一个错误或任何东西;

我也尝试使用常规路由方法,但它做同样的事情。

 this.match('/developer/:id', auth.requireApiToken, { controller: 'developer', action: 'show' }); 

我想捕获所有到达服务器的路由,并检查查询string中是否存在api标记。 如果不存在,则发送未经授权的响应,如果存在则进行检查,如果所有的都继续路由到正确的路由/控制器。 你如何利用机车来实现这一点,并保持路线不会超时?

你的requireApiToken应该作为一个适当的中间件,这是不(它只是console.log的东西)。

使用中间件,您需要发回一个响应,或使用next函数继续运行中间件链:

 var Authenticator = function () { this.requireApiToken = function(req, res, next) { console.log('requireApiToken'); next(); }; }; module.exports = Authenticator; 

此外,机车复制Express的一些function,所以你可以直接使用它们,而不必使用this.express来使它们工作。 所以这也应该工作(在config/environment/*.js ):

 var auth = new Authenticator; this.use(auth.requestApiToken);