Ember.js 销毁记录时出错

Ember.js Error while destroying record

我正在尝试销毁记录,但出现此错误

An adapter cannot assign a new id to a record that already has an id.
[…] had id: 25 and you tried to update it with null. This likely happened because
your server returned data in response to a find or update that had a different
id than the one you sent.

我的 REST API returns 一个 200 带有空对象响应的状态代码 {}。我认为这就是问题所在,所以我一直在尝试自定义几个序列化程序挂钩(normalizeDeleteRecordResponseextractDeleteRecord,甚至只是 normalizeResponse),但其中 none 实际上得到了打电话。

查看我的堆栈跟踪,错误似乎在 didSaveRecord 挂钩中,我假设它正在接收空的 JSON 有效负载并将其传递给 updateId

你的 API delete 应该 return 204 状态码

Ember 数据的默认适配器遵循 JSON API specification so when deleting a record(或规范中所称的资源),您应该 return 一个 204 No Content 响应(无内容) 或 200 OK if returning 其他元数据(必须位于名为 meta 的节点中)。仅 return 使用 200 OK 空对象在规范中是无效的,您最好的解决方案是修复其余部分 api 以遵循规范。

现在,如果这完全不可能,您可以通过基于 JSONAPIAdapter 创建自定义适配器然后覆盖 deleteRecord 来解决此问题。可能是这样的,基于 default implementation:

deleteRecord(store, type, snapshot) {
  var id = snapshot.id;

  return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE")
    .then(response => {
      if(Object.keys(response).length === 0) {
        return null; // Return null instead of an empty object, this won't trigger any serializers or trying to push new data to the store
      }
      return response;
    });
}