The Learner
The Learner

Reputation: 3917

node js calling functions

I am writing a big program (in size) using node js/Express.

I have multiple app.post functions and all. so, most of them need to do validation on coming Request and send a response.

So, I am created a function called Validate(); if the validation fails I will send the response to telling " please try again with information where validation Failed".

so, I created

function validate() { ...}

in the

app.post('/',function(req,res){
...

validate();
}

All the required parameters in req I am writing to a DB so I can access any where so that is not the problem now. Issue is : How do I send the "res" object. write now in validate if I try to call res. it will complain it is not defined.

so how to resolve this.

2) I tried to write the response of validate() in DB. and after that I tried to call the res: that is :

app.post('/',function(req,res){
...

validate();

res ..
}

As node is asyc this function validate response is not used by the res.

has any one come across issue like this

Upvotes: 4

Views: 46140

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

You should pass them as arguments:

function validate(req, res) {
    // ...
}
app.post('/', function (req, res) {
    validate(req, res);

    // ...
});

You can also define it as a custom middleware, calling a 3rd argument, next, when the request is deemed valid and pass it to app.post as another callback:

function validate(req, res, next) {
    var isValid = ...;

    if (isValid) {
        next();
    } else {
        res.send("please try again");
    }
}
app.post('/', validate, function (req, res) {
    // validation has already passed by this point...
});

Error handling in Express may also be useful with next(err).

Upvotes: 10

Related Questions