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);
我要做什么?
——比;添加变量'a'和'b',并将响应发送给用户。
我知道这是非常初级的东西,但是我无法通过谷歌找到我要找的答案。如果你能帮助我,我将不胜感激。
一种方法是将您的函数修复为正确的中间件,因为看起来您想将其用作中间件。例如:
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);
})
看一下这个,了解更多关于如何在Express中编写中间件的信息。
你的代码有一些问题。
app.get()
方法接受一个回调函数作为它的第二个参数,但是你传递的是sampler
函数。sampler
应在回调函数内部调用。
和s
变量是不可访问的,因为它的作用域仅在sampler
函数内。要访问该函数,必须调用该函数并将返回值存储到变量中。
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);