javascript - Before filter for all post requests in node.js -
i have below code in 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 request made /users/adduser
, go users.js
in routes folder.
now want add filter capture post requests , validations , if conditions satisfied post should go handler.
i.e if /users/adduser
post request, before going method in users.js in routes folder, should able capture request , stop if condition not met.
update 1 having app.use function, in result getting undefined not waiting till function 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; // tried next(); } } }) };
you can write simple middleware function that:
var validator = function(req, res, next) { // if request wasn't post request, pass along next handler immediately. if (req.method !== 'post') return next(); // perform validations. check(req.body, function(err) { // validation failed, or error occurred during 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 @ can insert middleware, kind of depend on how app structured.
one option:
app.use('/users', validator, users);
or, if have separate router /users
(in ./routes/users.js
):
router.use(validator);
or, if have separate post
route /users/adduser
:
router.post('/adduser', validator, function(req, res) { ... });
in last case don't have check req.method
in validator middleware because it's limited post
handler anyway.
Comments
Post a Comment