【问题标题】:backbone.js - model.save() generate wrong PUT url pathBackbone.js - model.save() 生成错误的 PUT url 路径
【发布时间】:2015-09-23 18:59:55
【问题描述】:

我讨厌问这些奇怪的问题,但无法避免这个问题。

我有“选项”视图,在创建时将“选项”模型作为参数传递。

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 服务器上实际上不存在此 URL。但我认为PUT URL更新模型的正确路径应该如下:

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

当我用Postman Rest 客户端测试这个 PUT url (http://localhost:13791/api/options/id_of_the_entity_to_be_updated) 时,它运行良好。

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

请给我一些建议,我应该如何解决这个问题。

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

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”。

【问题讨论】:

    标签: javascript rest backbone.js


    【解决方案1】:

    在您的模型中,您应该使用urlRoot 而不是url

    urlRoot: '/api/options/'
    

    【讨论】:

    • 当我在问题中写下“发现问题”部分时,我没有看到您的答案。无论如何,这是正确的答案,所以我勾选正确。
    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多