gpt4 book ai didi

node.js - 在express.js中完成处理请求

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:30 25 4
gpt4 key购买 nike

当我有一个简单的函数处理请求时,我可以使用 res.end()return 在任何时候结束它(发生了一些错误/不正确的数据等)

get('/', function (req, res) {
if (!req.param('id')) {
res.send('Must provide ID!');
res.end(); // <-- response is ready, send it to client
return; // <-- request processing stops here, get() finishes
}
// do other stuff
res.send('ok'); // <-- this can never overlap with the previous res.send()
});

但是,如果有函数嵌入到其他函数中,return只会退出最后一个

get('/', function (req, res) {
validate(req);
// do other stuff
res.send('ok'); // <-- this can cause errors? res was ended already
});

function validate(req, res) {
if (!req.param('id')) {
res.send('Must provide ID!');
res.end(); // <-- send response to client
return; // <-- this one exists only from validate()
}
}

我相信应该调用将响应发送到客户端res.end(),但是如何停止进一步的代码处理 - 即从所有函数返回?

最佳答案

不可能从被调用的函数返回,只需使用如下回调:

function validate(req, res, callback) {
if (!req.param('id')) {
res.send('Must provide ID!');
res.end();
} else {
callback();
}
}

get('/', function (req, res) {
validate(req, function () {
res.send('ok');
});
});

关于node.js - 在express.js中完成处理请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22018217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com