ajax在节点js中获取请求expression

我正在为我的Node js技能工作。

我想用点击button来添加一些数据给MongoDB。

客户端代码如下所示:

$(function() { $('#add').click(function(){ $.ajax({ type: "GET", url: "/item/<%= products._id %>/add" }).done (function (data) { alert(data); console.log(data); }); }); }); <button type="submit" id="add" class="btn btn-primary">Interessted</button> 

服务器端代码是这样的:

  app.get('/item/:id/add', function(req, res) { Listing.findByIdAndUpdate( { _id : req.params.id}, { $push : {"product.interessteduser": req.user._id }}, { safe: true, upsert: true}, function(err, model) { if(err){ console.log(err); } }); }); 

代码对我来说是完美的,但是如果我稍微等一下,我会在控制台中得到另一个请求。

看起来像这样:

 GET /item/557eec02aa1046b805190207/add 200 120001ms GET /item/557eeb82aa1046b805190206/add 200 120000ms 

所以每次请求/ item /:id /添加并等待120000ms我得到另一个请求。 如何阻止这个?

我想点击button一次做/ item / 557eeb82aa1046b805190206 /添加获取请求,这一切。

您从不回应请求。 如果您没有回应,浏览器会在两分钟后重试请求。 尝试类似

 res.send("success"); 

然而,当你得到答案的时候,它总是优雅地编写单独的函数来处理发送成功/失败的情况,所以一旦被testing,就应该使用它并且避免这些错误。


  --Expose these two helper methods as module and always use that module to send the result or error response at last. exports.send_success = function (res, data) { res.writeHead(200, {"Content-Type": "application/json"}); var output = { error: null, data: data }; res.end(JSON.stringify(output)); }; exports.send_failure = function (res, err) { var code = exports.http_code_for_error(err); res.writeHead(code, { "Content-Type" : "application/json" }); res.end(exports.error_for_resp(err)); }; function (err, results) { if (err) { helper.send_failure(res, err); } else { helper.send_success(res, results); } } 

添加res.end();return false; 到你的代码

尝试这样的事情

  app.get('/item/:id/add', function(req, res) { Listing.findByIdAndUpdate( { _id : req.params.id}, { $push : {"product.interessteduser": req.user._id }}, { safe: true, upsert: true}, function(err, model) { if(err){ console.log(err); }else{ res.json({'status':'200','message':'Success!'}); res.end(); return false; } }); });