Loopback:通过ajax发布一个对象数组

我正在努力与使用Ajax的环回问题。 我尝试通过jQuery函数.ajax()一个对象的数组,但我只是根本不能。 服务器总是给我一个422错误(不可处理的实体)。

好奇的是:我可以使用GUI资源pipe理器或命令行完成相同的请求。

我有两个模型:通过hasMany / belongsTo关系关联的Nemo和PendingUpdates(我已经截断了它们,使其更具可读性):

 // nemo.json { "name": "Nemo", "base": "PersistedModel", "properties": { "id": { "type": "Number", "id": true, "required": false, "generated": true } }, "relations": { "pendingUpdates": { "type": "hasMany", "model": "PendingUpdate", "foreignKey": "nId" } } } 

 // pending-update.json { "name": "PendingUpdate", "base": "PersistedModel", "properties": { "id": { "type": "Number", "id": true, "required": false, "generated": true }, "nId": { "type": "Number", "required": true }, "parameter": { "type": "String", "required": false }, "requestType": { "type": "Number", "required": true } }, "relations": { "nemo": { "type": "belongsTo", "model": "Nemo", "foreignKey": "nId" } } } 

这是事情:我尝试POST一个pendingUpdates数组。 使用strongloop资源pipe理器,我只是发布这个:on /Nemos/{id}/pendingUpdates与id:2和数据: [{"requestType": 3, "parameter": "stuff"}, {"requestType": 2, "parameter": "otherStuff"}] 。 我有一个200响应代码与正文中创build的对象。

但是,当我尝试发送完全相同的请求客户端使用jQuery,我得到了422。

以下是摘录:

 var data = [ {"requestType": 3, "parameter": "stuff"}, {"requestType": 2, "parameter": "otherStuff"} ]; $.ajax("/api/Nemos/2/pendingUpdates?access_token=xxxxxxxxx", { data: data, headers: { Accept: "application/json", contentType: "application/json" }, method: "POST" }).done(success) .fail(fail); 

我已经尝试使用直接data{data}{"data": data}JSON.stringify({"data": data})JSON.stringify(data)

有人可以帮我吗?

非常感谢你,

Bjorge

好的,经过一天的时间和控制台和WireShark的尝试,我发现什么是错的; 我会在这里写下答案,以帮助有同样问题的未来人士。

  • 首先,正如我在我的评论中所假设的那样,麻烦并不是来自LoopBack,它会误解发送给它的数据,而是来自jQuery:发送POST请求,但没有任何数据。
  • 然后,我设法发送一个适当的POST请求(即与一个JSON对象,而不是一个数组)。 我能够看到有两个Content-Type标头。 我改变了我的function,只发送一个。
  • 最后,我能够使请求运行正确与下面的代码:

 var data = [ {"requestType": 3, "parameter": "stuff"}, {"requestType": 2, "parameter": "otherStuff"} ]; $.ajax("/api/Nemos/2/pendingUpdates?access_token=xxxxxxxxx"), { data: JSON.stringify(data), accept: "application/json", contentType: "application/json", method: "POST" }).done(success) .fail(fail); 

我希望将来能帮助别人。