backbone.js - model.save()生成错误的PUT url路径

时间:2015-09-23 18:59:55

标签: javascript rest backbone.js

我不想问这些奇怪的问题,但却无法避免这个问题。

我有"选项"查看"选项"模型在创建时作为参数传递。

var optionView = new OptionView({ model: option });
this.$el.find('div#optionsBoard').append( optionView.render().el );

在此视图中,当用户点击"投票"按钮," voteCount"模型的属性将递增。

events: { 'click .button-vote': 'processVote' },

processVote: function (e) {
        var voteCounted = this.model.get('voteCount');
        this.model.set('voteCount', voteCounted++);

        console.log(this.model.id); // has a Id value
        console.log(this.model.isNew()); // false

        this.model.save(); // occurs problem here
        e.preventDefault();
    },

将模型保存回服务器时出现问题如下:

PUT http://localhost:13791/api/options/ 404 (Not Found)

是的,这个网址实际上并不存在于我的REST API服务器上。但我相信PUT URL更新模型的正确路径应如下:

PUT http://localhost:13791/api/options/id_of_the_entity_to_be_updated

当我使用Postman Rest客户端测试此PUT网址(http://localhost:13791/api/options/id_of_the_entity_to_be_updated)时,它运行正常。

所以我认为问题出现是因为Backbone model.save()方法没有将id_of_the_entity_to_be_updated添加到PUT网址。

请告诉我一些如何解决这个问题的方法。

作为附加说明,这是我的选项"模型设置代码。

define([
    'backbone'
], function (Backbone) {

    var Option = Backbone.Model.extend({
        idAttribute: "_id",

        defaults: {
            name: '',
            location: '',
            link: '',
            voteCount: 0,
            expiredDate: Date.now(),
            imageName: ''
        },

        url: '/api/options/',

        readFile: function(file) {
            var reader = new FileReader();
            // closure to capture the file information.
            reader.onload = ( function(theFile, that) {
                return function(e) {
                    that.set({filename: theFile.name, data: e.target.result});
                    that.set({imageUrl: theFile.name});
                    console.log(e.target.result);
                };
            })(file, this);

            // Read in the image file as a data URL.
            reader.readAsDataURL(file);
        }
    });

    return Option;

});

发现问题

我的坏。在" Option"模型设置,它应该是" urlRoot"而不是" url"。

1 个答案:

答案 0 :(得分:1)

在您的模型中,您应该使用urlRoot代替url

urlRoot: '/api/options/'