【问题标题】:RESTful Express Mongoose & Backbone - Backbone model.remove() not workingRESTful Express Mongoose & Backbone - Backbone model.remove() 不工作
【发布时间】:2014-05-17 21:18:42
【问题描述】:

我正在使用 Express、Mongoose 和 Backbone 和 Marionette 开发一个 Node 应用程序。

除删除路由外,所有路由都运行良好。

如果我调用 this.model.destroy,我总是会得到这个错误:

DELETE http://localhost:3000/api/user 404 (Not Found) 

404 在 Express 的删除路由中返回,就像 Express 不支持它一样,但我在网络上看到了许多使用它的示例。

这是我的设置:


Mongoose 架构:

var UserSchema = new mongoose.Schema(
{
    name: String,
    email: String,
    age: Number
});

User = mongoose.model('User', UserSchema);

ExpressJS 路由:(不工作)

app.del('/api/user/:id', user.remove);

app.delete('/api/user/:id', user.remove);

这个路由被主干model.destroy()调用,但是返回错误404。


ExpressJS user.js 控制器:(工作但由于之前的 404 无法到达)

exports.remove = function(req, res)
{
  var id = req.params.id;

  User.findById(req.params.id, function(err, user) 
  {
      user.remove(function(err) 
      {
          if(err) res.json(err);
          res.json('all good');
      });
   });
};

BackboneJS 模型

var User = Backbone.Model.extend({
    idAttribute: "_id",
    url: '/api/user/',
});

BackboneJS 客户端视图

var UserView = Backbone.Marionette.ItemView.extend(
{
    template: Handlebars.compile($('#userView').html()),
    events: 
    {
        'click .delete-button': 'deleteUser'
    },
    deleteUser: function(event)
    {
        this.model.remove();
    }
});

我总是收到这个错误:

DELETE http://localhost:3000/api/user 404 (Not Found) 

如果我使用这个直接的 ajax 调用它会起作用:

jQuery.ajax({
  url:'/api/user/' + this.model.id,
  type: 'DELETE',
  success:function(data, textStatus, jqXHR)
  {

  }
});

那么,如果我通过 Ajax 调用路由,如果 Backbone 内部也使用 Ajax,为什么这会起作用?为什么Backbone 做不出这么简单的model.destroy()?

有没有办法像上面的 Ajax 示例一样配置 Backbone Model.destroy 方法以正常工作?谢谢

【问题讨论】:

  • 在执行 DELETE 请求时,似乎没有设置模型的 id。 HTTP DELETE 请求 url 不应该是,例如,localhost:3000/api/user/35,其中 35 是用户的 id?它看起来不像正在发送用户的 id...

标签: ajax node.js backbone.js express mongoose


【解决方案1】:

发现问题。 Backbone model.remove() 没有发送 id,因为我以这种方式使用“url”:

Backbone.Model.extend({
    url: '/users',
    //...
});

这将告诉 Backbone 使用 /users 作为所有操作的 URL。

为了确保使用“url”发送id,可以使用一个函数:

url: function() { 
    return '/list_items/' + encodeURIComponent(this.id) 
}

或者甚至更好地使用“urlRoot”而不是“url”,让默认的“url”函数添加id:

urlRoot: '/users'

使用 urlRoot 像魅力一样工作

【讨论】:

  • 是的,urlRoot 更简单。如果使用 urlRoot,则不需要将 url 定义为函数。将 url 定义为函数更好地保留给使用查询参数的更复杂的 url。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
相关资源
最近更新 更多