【问题标题】:Ember JS: Assertion Failed: `AdapterError` expects json-api formatted errors arrayEmber JS:断言失败:`AdapterError` 需要 json-api 格式的错误数组
【发布时间】:2018-01-30 18:33:36
【问题描述】:

我正在使用 JSONAPIAdapter 制作我的第一个 Ember/Phoenix 应用程序。当进行发布请求时,Ember 会以 Assertion Failed: AdapterError expects json-api formatted errors array.

进行响应

下面是相关代码:

适配器/application.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import config from '../config/environment';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {

});

序列化器/application.js

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({

});

请求负载:

{
    "data": {
        "attributes": {
            "name": ""
        },
        "relationships": {
            "user": {
                "data": {
                    "type": "users",
                    "id": "1"
                }
            }
        },
        "type": "listings"
    }
}

响应负载:

{"errors":{"name":["can't be blank"]}}

为什么 Ember 总是给我这个错误?

【问题讨论】:

    标签: ember.js json-api


    【解决方案1】:

    您的响应负载不正确。您正在使用 json-api。所以你的有效载荷必须遵循json-api specification。您的请求有效负载看起来是正确的。但是看看错误必须是serialized。 一个 json-api 错误响应必须包含一个根键 "errors" 包含一个错误对象数组。关于documenation,一个错误可能包含多个成员,但最重要的两个是detailsource

    这是一个例子:

    {
      "errors":[
        {
           "detail": "can't be blank",
           "source": {
             "pointer": "data/attributes/name"
           }
        }
      ]
    }
    

    source-key 包含一个包含 json-api-pointer 的 json-object。借助此指针 信息,ember 的 JSONAPI-Adapter 将错误添加到记录的相应属性中。请注意,您的后端需要发送 422 HTTP 状态代码(无法处理的实体)。

    如果可行,您可以在客户端执行类似操作:

    {{#each model.errors.name as |error|}}
      <div class="error">
        {{error.message}}
      </div>
    {{/each}}
    

    您如何在后端序列化您的错误?你在用ja_serializer吗?如果没有,我会推荐它,因为 ja_serializer 默认可以序列化 json-api-errors。

    【讨论】:

      【解决方案2】:

      已经被 wuarmin 链接的documentation 明确指出(大写是他们的,斜体是我的):

      错误对象必须作为 数组返回,以错误为键

      您的 API 响应'errors 键具有单个对象作为值,而不是数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 2012-10-03
        • 2018-09-18
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多