2014년 12월 26일 금요일

[Express-js] How can I handle body data before app.post()?

- I am use express for my application. I used:

app.post('/abc', function (req, res, next) {
if (!req.body.udid) {
// Do something 
}
});

app.post('/xyz', function (req, res, next) {
if (!req.body.udid) {
// Do something 
}
});

All my app.post() functions, I have to check udid param. How can I check it before it goto app.post function? Thank you.



> - I am use express for my application. I used:
>
> app.post('/abc', function (req, res, next) {
> if (!req.body.udid) {
> // Do something
> }
> });
>
> app.post('/xyz', function (req, res, next) {
> if (!req.body.udid) {
> // Do something
> }
> });
>
> All my app.post() functions, I have to check udid param. How can I check it before it goto app.post function?
Write a middleware to do that, then include it in each applicable route. Untested code follows:


function checkUdid(req, res, next) {
  if (!req.body.udid) {
    return next(new Error('No UDID found'));
  }
  next();
}

app.post('/abc', checkUdid, function (req, res, next) {
  // UDID has already been checked at this point
});

app.post('/xyz', checkUdid, function (req, res, next) {
  // UDID has already been checked at this point
});


댓글 없음:

댓글 쓰기