Home > database >  Use functions with Express in Node JS: Beginner
Use functions with Express in Node JS: Beginner

Time:01-19

function sampler(){
    const a=1;
    const b =2;
    const s=a b;
    return s;
}

app.use(bodyParser.json())
app.get('/',(sampler),(req,res)=>{
  res.send(s);
})

app.listen(2300);

What I'm trying to do?

--> Add the variables 'a' and 'b' and send the response to the user.

I know this is pretty beginner stuff, but I couldn't find the answer I'm looking for through Googling. I would appreciate any help on this.

CodePudding user response:

One way would be to fix your function to be a correct middleware, since it looks like you want to use it as a middleware. For example:

const sampler = function (req, res, next) {
    const a = 1;
    const b = 2;
    const s = a   b;
    req.sum= s.toString();
    next();
}

app.get('/',sampler,(req,res)=>{
    res.send(req.sum);
})

Take a look at this to learn more about how to write a middleware in Express.

CodePudding user response:

There are some problems with your code.

The app.get() method takes a callback function as its second argument, but you are passing the sampler function instead. sampler should be invoked inside the callback function.

And s variable is not accessible because it's scope is only inside sampler function. You must call the function and store returned value to a variable to access it.

function sampler() {
  const a = 1;
  const b = 2;
  const s = a   b;
  return s;
}

app.get('/', (req, res) => {
  const s = sampler();
  res.send(s.toString());
});

app.listen(2300);
  • Related