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

2 Answers 2

1

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.

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

Comments

0

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

1 Comment

In addition I would also look into controllers if you want to separate the routes and the logic.

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.