Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js calling functions

Tags:

node.js

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

like image 563
The Learner Avatar asked Jan 15 '23 18:01

The Learner


1 Answers

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).

like image 145
Jonathan Lonowski Avatar answered Jan 21 '23 09:01

Jonathan Lonowski