Node.js 无法处理执行类似于以下 jQuery/Zepto XHR 模式的客户端代码:
$.ajax({
type: 'POST',
url: '/someUrl',
success: function(response) {
$.ajax({ // ... do another XHR
在其他框架中,我已经完成了这个(在另一个 XHR 请求中启动 XHR 请求)模式。我已阅读有关Node.js 错误:发送后无法设置标头以及 Node.js 服务器的基于事件的模型如何工作的信息。换句话说,第一个 XHR 请求没有调用 res.end() 所以当第二个 XHR 请求被调用时 Node.js 抱怨(在一个连续的循环中)。
我的问题是:任何人都可以推荐一种替代模式来链接 XHR 请求客户端吗?我可以在 Node.js 服务器端做些什么来保持现有的客户端模式吗?
根据接受
的答案更新错误肯定在我自己的服务器端代码中。一个简单的验证函数抛出了一个错误,但在捕获它时,只调用了 res.end()。由于某种原因,我调用 res.end() 的假设会立即停止函数的执行。在这种情况下,插入“return”会在将 JSON 消息发送到客户端后立即停止执行。
if (_.isEmpty(req.body)) {
res.end(JSON.stringify({'Error':'POST required'}));
// suppose 'return' is needed here as well
return
} else {
try {
if (_.has(req.body, 'id')) {
id = parseInt(req.body['id']);
} else {
throw {'Error':'Missing param in req.body'};
} // end if
} catch(err) {
res.end(JSON.stringify({'Error':'Missing key(s)','Keys':_.keys(req.body)}));
// without a return here, the code below this 'do some more work' would
// be executed
return
} // end else
// do some more work
// without the above 'return''s the code would
// a) make a database call
// b) call res.end() again!!! <-- bad.