Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before filter for all post requests in node.js

I have the below code in my node.js app.js:

var express = require('express')
    ,cors = require('cors')
    ,app=express();
    var users = require('./routes/users');
    //some other codes
    .....
    app.use('/', routes);
    app.use('/users', users );

If a request is made to /users/adduser, it will go to the users.js in the routes folder.

Now I want to add a filter which will capture all the POST requests and do some validations and only if the conditions are satisfied the POST should go to its handler.

I.e if i get a /users/adduser with a POST request, before going to the method in the users.js in the routes folder, I should be able to capture that request and stop it if the condition is not met.

UPDATE 1 Now i am having this app.use function, but in the result i am getting undefined as its not waiting till the function is returning value

app.use(function (req, res, next) {
    req.db = db;
    if (req.method != "POST") {
        next();
    }
    else {
        var userData = req.body;
        var result = Check(userData);
        if(result){
        next();            
        }
    }
});

function Check(userdata) { 

    var url = "someurl"+userdata.Id;

    var request = require("request");
    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            if (response.toJSON().body.id == userId) { 
                return true;
                // i also tried next();
            }  
        }
    })
};
like image 259
Vignesh Subramanian Avatar asked Jun 23 '26 01:06

Vignesh Subramanian


1 Answers

You can write a simple middleware function for that:

var validator = function(req, res, next) {
  // If the request wasn't a POST request, pass along to the next handler immediately.
  if (req.method !== 'POST') return next();

  // Perform your validations.
  Check(req.body, function(err) {
    // Validation failed, or an error occurred during the external request.
    if (err) return res.sendStatus(400);
    // Validation passed.
    return next();
  });
};

function Check(userdata, callback) { 
  var url     = "someurl"+userdata.Id;
  var request = require("request");
  request({ url: url, json: true }, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      if (response.toJSON().body.id === userId) { 
        return callback(null, true);
      }
    }
    return callback(new Error());
  })
};

You have various points at which you can insert this middleware, which kind of depend on how exactly your app is structured.

One option:

app.use('/users', validator, users);

Or, if you have a separate router for /users (in ./routes/users.js):

router.use(validator);

Or, if you have a separate POST route for /users/adduser:

router.post('/adduser', validator, function(req, res) { ... });

In the last case you don't have to check req.method in the validator middleware because it's limited to the POST handler anyway.

like image 164
robertklep Avatar answered Jun 25 '26 15:06

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!