Gal Ratzkin Gal Ratzkin - 1 year ago 43
Javascript Question

Proper way to use javascript with expressjs in node

I'm trying to learn JavaScript and full-stack development and I can't quite wrap my head around how to use express with JavaScript properly ....

my question goes like this :

in every tutorial iv'e seen online the following syntax is being used :

app.get('/',function(request,response,next){

var something = request.body.something;
if(something){do stuff...}
else{do other stuff...}

})


what if I wan't to not use anonymous functions but predefined named ones?

how would I use them in express methods?

will something like this be o.k? :

function doStuffwithTheRequest(request,response,next){

var something = request.body.something;
if(something){do stuff...}
else{do other stuff...}

};


app.get('/',doStuffwithTheRequest());


and if so what would be the proper way to pass the parameters in this manner ?

Iv'e tried coding like this but i cant seem to be able to pass the parameters to the function when it's predefined ...

Answer Source

The way you are doing it, you are calling the named function with no arguments. You should just pass the function itself:

app.get('/',doStuffwithTheRequest);

Just make sure the function definition has the correct arguments (req, res, next), which it does in your example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download