ajax在节点js express中获取请求

时间:2015-06-28 16:35:53

标签: jquery ajax node.js mongodb

我在我的Node js Skills上工作了一点点。

我想使用按钮点击向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

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

我想按一下/ item / 557eeb82aa1046b805190206 /添加获取请求以及全部。

3 个答案:

答案 0 :(得分:4)

您永远不会回复此请求。如果您没有回复,浏览器会在两分钟后重试请求。尝试像

这样的东西
res.send("success");

答案 1 :(得分:0)

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

  --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);
            }
    }

答案 2 :(得分:0)

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;
             }

        });
   });