简体   繁体   English

在 Node JS 中使用 Express 函数:初学者

[英]Use functions with Express in Node JS: Beginner

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. --> 添加变量“a”和“b”并将响应发送给用户。

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.我将不胜感激任何帮助。

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.一种方法是将您的 function 修复为正确的中间件,因为看起来您想将其用作中间件。 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.看看这个以了解有关如何在 Express 中编写中间件的更多信息。

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. app.get()方法将回调 function 作为其第二个参数,但您传递的是sampler function。 sampler should be invoked inside the callback function.应该在回调 function 中调用sampler

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.并且s变量不可访问,因为它的 scope 仅在sampler function 内。您必须调用 function 并将返回值存储到变量才能访问它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM