0

Here is what i am trying to do. I am writing an app in nodejs express and trying to divide different parts of apps in separate modules. I have some problem access this variable in middleware functions

Below is my routes module

"use strict";
function route(params){
  var app = params.app;
  var ApiHelper = require('../library/apiHelper').init(params);
  //get
  app.get('/', Api.index);
  app.get('/check', ApiHelper.validateRequest, Api.check);
}
module.exports = route;

My ApiHelper class

"use strict";
function ApiHelper(params){
  this.params = params;
}
module.exports.init = function (params){
  return new ApiHelper(params);
};
ApiHelper.prototype.validateRequest = function validateRequest(req, res, next){
  console.log(this.params);//this is undefined
};

I am unable to access this.params in validateRequest object of the ApiHelper

Yalamber
  • 7,360
  • 15
  • 63
  • 89

1 Answers1

0

You're losing the binding by passing only the validateRequest method. You can rebind it like this:

app.get('/check', ApiHelper.validateRequest.bind(ApiHelper), Api.check);
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Hello, I actually made it work this way http://pastebin.com/TUewSQ10 Can you recommend me which is better way to make this work? – Yalamber May 01 '13 at 10:46
  • I would use the method in your Pastebin code myself :) BTW, you're installing `express.bodyParser()` for every call to `validateRequest`; middleware should be installed just once (during server configuration). – robertklep May 01 '13 at 10:53
  • hello, I tried to keep body parser in the validaterequest as suggested here http://stackoverflow.com/questions/12418372/node-js-express-correct-use-of-bodyparser-middleware. Am i doing it correct? – Yalamber May 01 '13 at 10:58
  • The normal way of using it is to just declare it once, for all routes, unless you really have to worry about your site being attacked (like the person in the posting you link to seems to be worried about). Also, `bodyParser` only makes sense for `POST` routes, and you're using it on a `GET` route. – robertklep May 01 '13 at 11:44
  • Great. So i can just pass it to POST request only right? just call body parser part in some middleware will do it right? – Yalamber May 01 '13 at 12:06
  • 1
    Just use `app.use(express.bodyParser());`. Or, if you want to pass it to `POST` routes only: `var bodyParser = express.bodyParser(); app.post('/route', bodyParser, ...);` – robertklep May 01 '13 at 12:20
  • Can we do like this inside validateRequest if('POST' == req.method){ app.use(express.bodyParser()); } – Yalamber May 01 '13 at 12:25
  • No, you cannot insert middleware *during* a request. – robertklep May 01 '13 at 12:30
  • hmm ok, i will add body parser in app.post – Yalamber May 01 '13 at 16:12