在我的express应用程序中,当调用下面的DELETE方法时,将立即调用GET方法,这在我的角度代码中给我一个错误,该错误表示应该是一个对象但有一个数组。

当我在DELETE方法中显式执行res.send(204);时,为什么调用GET方法,该如何解决呢?

服务器控制台:

DELETE /notes/5357ff1d91340db03d000001 204 4ms
GET /notes 200 2ms - 2b


特快专递路线

exports.get = function (db) {
    return function (req, res) {

        var collection = db.get('notes');

        collection.find({}, {}, function (e, docs) {
            res.send(docs);
        });
    };
};

exports.delete = function(db) {
    return function(req, res) {

        var note_id = req.params.id;
        var collection = db.get('notes');

        collection.remove(
            { _id: note_id },

            function(err, doc) {

                // If it failed, return error
                if (err) {
                    res.send("There was a problem deleting that note from the database.");
                } else {
                    console.log('were in delete success');
                    res.send(204);
                }
            }
        );
    }
}


app.js

var note = require('./routes/note.js');
app.get('/notes', note.get(db));
app.post('/notes', note.create(db));
app.put('/notes/:id', note.update(db));
app.delete('/notes/:id', note.delete(db));


angularjs控制器

$scope.delete = function(note_id) {
  var note = noteService.get();
  note.$delete({id: note_id});
}


angularjs noteService

angular.module('express_example').factory('noteService',function($resource, SETTINGS) {

  return $resource(SETTINGS.base + '/notes/:id', { id: '@id' },
      {
        //query:  { method: 'GET', isArray: true },
        //create: { method: 'POST', isArray: true },
        update: { method: 'PUT' }
        //delete: { method: 'DELETE', isArray: true }
      });
});


**更新**
为了帮助绘制图片,这是我得到的角度误差:

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array http://errors.angularjs.org/1.2.16/$resource/badcfg?p0=object&p1=array


我假设我收到此错误,因为我的delete方法正在调用我的get方法(以某种方式),并且get方法返回整个集合。

最佳答案

服务器端

您正在从delete函数的集合中删除元素。这是异步完成的,并在完成后调用回调。

在这段时间内,其他请求将被执行,这就是为什么GET请求在您的DELETE请求完成之前被执行的原因。

get函数中也会发生同样的情况,您正尝试从集合中查找元素,而该函数太异步了。

但这仅是服务器端并且很好,它应该以这种方式工作,您的问题位于客户端。

客户端

如果要在获取便笺后删除便笺,则必须在角度控制器中使用回调函数,仅当您收到便笺时才调用该函数(如果需要帮助,请向我们显示您的noteService角度代码)。

这是一些基本的JavaScript理解问题,动作通常是异步进行的,您需要回调才能具有执行链。

也许尝试做这样的事情:

$scope.delete = function(note_id) {
    var note = noteService.get({ id: note_id }, function()
    {
        note.$delete();
    });
}


但是您的代码没有意义,为什么get中有一个$scope.delete?为什么不做以下简单的事情:

$scope.delete = function(note_id) {
    noteService.delete({ id: note_id });
}


错误

我认为由于服务器在exports.delete函数中发送的内容而导致出现此错误。当angular需要一个对象时,您将发送一个字符串或根本不发送任何内容(REST API从不发送字符串)。您应该发送类似的内容:

res.send({
    results: [],
    errors: [
        "Your error"
    ]
});

07-24 09:51
查看更多