javascript - 在 $.ajax 之后从未调用完成函数

标签 javascript jquery node.js ajax

我对这一切(包括 Javascript 回调和 ES6)有点陌生。我正在使用 NodeJS + Express + MongoDB。

我正在调用 Ajax 函数来更新项目,但 Ajax 调用从未成功。

这是我的 Ajax 调用(从 React 调用)

editBug : function(bug){

    console.log('about to edit bug with these values',bug);
    $.ajax({
        url:'/api/bugs',
        method: 'PUT',
        data:bug
    })
    .done((jqxhr) => {
        console.log('succcess while editing the bug');
        this.setState({successVisible : true});
    })
    .fail((jqxhr) => {
        console.log('error : ' + jqxhr);
    })  
},

这是我的 API 函数:

app.put('/api/bugs',function(req,res){

    //console.log('req',req);
    console.log('query string : ',req.query);
    console.log('query params : ',req.params);
    console.log('query body: ',req.body);
    let id = new ObjectID(req.body._id);
    req.body._id = new ObjectID(req.body._id);

    db.collection('bugs').replaceOne(
        {_id:id},
        req.body,
        function(err,result){
            assert.equal(err,null);
            console.log('Successfull replace!');
            res.status(200);
        }
    );
});

Successfull replace! 日志正确显示在服务器端。 about to edit bug with these values 正确显示在正面。但是 success while editing the bug log 并没有显示在前端,似乎 .done 调用从未执行过。

最佳答案

问题是您没有将任何响应发送回 Node 端的浏览器。试试下面的代码片段,你应该可以开始了

另外,我想指出您应该处理这些错误。如果出现问题,更新 bugs 时,最佳做法是使用 500 状态代码通知浏览器,指示预期操作失败。我在下面的片段中添加了这个方面

app.put('/api/bugs', function(req, res) {

  //console.log('req',req);
  console.log('query string : ', req.query);
  console.log('query params : ', req.params);
  console.log('query body: ', req.body);
  let id = new ObjectID(req.body._id);
  req.body._id = new ObjectID(req.body._id);

  db.collection('bugs').replaceOne({
      _id: id
    },
    req.body,
    function(err, result) {
      if (err) {
        console.log('Failed replace');
        res.status(500).end(); // <- We set the response status code and end the request
      } else {
        assert.equal(err, null);
        console.log('Successfull replace!');
        res.status(200).end(); // <- We set the response status code and end the request
      }
    }
  );
});

关于javascript - 在 $.ajax 之后从未调用完成函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327926/

相关文章:

jquery - 用作 JQuery 选择器时, '>' 是什么意思?

javascript - 如何在 RegEx (Javascript) 中使用变量?

javascript - 只有在 if 语句中完成所有异步回调后才起作用

javascript - 单击时以编程方式关闭 Google map POI

javascript - 使用 JavaScript 访问 PrimeFaces 日历的禁用属性

javascript - 使用自定义标签值 jquery 获取元素 id

javascript - 如何在html5和jboss服务器中使用svgz文件

node.js - 我们可以在Socket.IO中将数据添加到房间吗

node.js - 为什么 Mongoose 查询在放入 Promise 函数时不起作用

node.js - Sequelize create 方法返回生成的主键?