4

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

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Jonathan. also In function declaration we mention the datatype. dont we need to mention the data type here
@TheLearner Nope. JavaScript variables are dynamic, so you just have to name them -- developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions. Though, if you're using another ECMAScript variant, such as TypeScript, then you might need to specify the types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.