node.js 节点js调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13908495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node js calling functions
提问by The Learner
I am writing a big program (in size) using node js/Express.
我正在使用 node js/Express 编写一个大程序(大小)。
I have multiple app.post functions and all. so, most of them need to do validation on coming Request and send a response.
我有多个 app.post 功能等等。因此,他们中的大多数需要对即将到来的请求进行验证并发送响应。
So, I am created a function called Validate(); if the validation fails I will send the response to telling " please try again with information where validation Failed".
因此,我创建了一个名为 Validate() 的函数;如果验证失败,我将发送响应告诉“请使用验证失败的信息再试一次”。
so, I created
所以,我创造了
function validate() { ...}
in the
在里面
app.post('/',function(req,res){
...
validate();
}
All the required parameters in req I am writing to a DB so I can access any where so that is not the problem now. Issue is : How do I send the "res" object. write now in validate if I try to call res. it will complain it is not defined.
我正在写入数据库的 req 中的所有必需参数,以便我可以访问任何位置,因此现在这不是问题。问题是:如何发送“res”对象。如果我尝试调用 res,请立即写入验证。它会抱怨它没有定义。
so how to resolve this.
那么如何解决这个问题。
2) I tried to write the response of validate() in DB. and after that I tried to call the res: that is :
2)我试图在数据库中编写validate()的响应。之后我尝试调用 res: 即:
app.post('/',function(req,res){
...
validate();
res ..
}
As node is asyc this function validate response is not used by the res.
由于节点是异步的,因此 res 不使用此功能验证响应。
has any one come across issue like this
有没有人遇到过这样的问题
回答by Jonathan Lonowski
You should pass them as arguments:
您应该将它们作为参数传递:
function validate(req, res) {
// ...
}
app.post('/', function (req, res) {
validate(req, res);
// ...
});
You can also define it as a custom middleware, calling a 3rd argument, next, when the request is deemed valid and pass it to app.postas another callback:
您还可以将其定义为自定义中间件,next当请求被认为有效时调用第三个参数,并将其app.post作为另一个callback参数传递给:
function validate(req, res, next) {
var isValid = ...;
if (isValid) {
next();
} else {
res.send("please try again");
}
}
app.post('/', validate, function (req, res) {
// validation has already passed by this point...
});
Error handlingin Express may also be useful with next(err).
Express 中的错误处理也可能对next(err).

