Ember data: Your server returned a hash with the key 0 but you have no mapping for it

前端 未结 3 1547
名媛妹妹
名媛妹妹 2021-01-21 12:07

I have a simple model and use the RESTadapter to get the data. The JSON request is executed, but then I receive the following error: \"Your server returned a hash with the key

相关标签:
3条回答
  • 2021-01-21 12:49

    If you don't have access to the server, it's pretty easy to modify the adapter. For the "GET" requests, you'll need to override find and findAll within your adapter:

    App.Store = DS.Store.extend({
      adapter: DS.RESTAdapter.create({
        find: function(store, type, id) {
          var root = this.rootForType(type), adapter = this;
    
          return this.ajax(this.buildURL(root, id), "GET").
          then(function(json){
            var updatedJSON = {};
            updatedJSON[root] = json;
            adapter.didFindRecord(store, type, {article: json}, id);
          }).then(null, DS.rejectionHandler);
        },
    
        findAll: function(store, type, since) {
          var root, adapter;
    
          root = this.rootForType(type);
          adapter = this;
    
          var resourceName = this.pluralize(root);
    
          return this.ajax(this.buildURL(root), "GET",{
            data: this.sinceQuery(since)
          }).then(function(json) {
            var updatedJSON = {};
            updatedJSON[resourceName] = json;
            adapter.didFindAll(store, type, updatedJSON);
          }).then(null, DS.rejectionHandler);
        }
      })
    });
    

    At the moment, these functions live in the source code here in rest_adapter.js.

    The difference here is where updatedJSON is defined in each of the functions. It takes the json from the server and constructs a new object with (hopefully) the correct key you need.

    0 讨论(0)
  • 2021-01-21 13:04

    The JSON you are looking for should have a root element

    {"articles": [ 
      { 
        "id": 1,
        "title": "Title 1"
      },
      {
        "id": 2,
        "title": "Title 2"
       }
      ]
    }
    

    You can find documentation in the Ember Docs RESTAdapter or at the JSONapi project

    0 讨论(0)
  • 2021-01-21 13:04

    @kiwiupover was 98% right, when having multiple records it should be pluralized to articles:

    {"articles": [
         { 
           "id": 1,
           "title": "Title 1"
         },
         {
           "id": 2,
           "title": "Title 2"
         }
    ]}
    
    0 讨论(0)
提交回复
热议问题