0

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. 
4

1 回答 1

0

问题不是你想的那样。由于回调,您的两个 XHR 是串行发生的,而不是并行发生的。在第success一个请求的整个请求/响应过程完成之前,第一个回调不会触发(node.js 已经调用了 response.end() 并且浏览器已经接收并解析了响应)。只有这样,第二个 XHR 才会开始。您拥有的客户端 AJAX 模式很好。它同样适用于 node.js 和任何其他 Web 服务器。

您的问题出在您的服务器端 node.js 代码中,但这不是节点中的错误或限制,而是您的编程错误。发布您的服务器端代码,我们可以帮助您追踪它。node.js 初学者通过一个简单的编码错误遇到这个错误是很常见的。

于 2012-02-18T05:52:40.930 回答