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);
我希望将来能帮助别人。
- 将客户端JS连接到服务器端的NodeJS应用程序
- ajax在节点js中获取请求expression
- 在浏览器中解压缩一个JSON数据文件,作为来自Node.js的静态文件
- (ab)使用node.js作为超级快速轮询和ajax服务器来更新数据库(类似于Google Spreadsheet方法)
- 如何使用FormData发送文件到Nodejs并让Node发送确认消息?
- Express res.renderredirect后无法工作
- 如何select一个表行数据,并将其发送到编辑模式使用jQuery,JavaScript和AJAX更新数据?
- 用nodejs在一个文件上写http请求
- io.connect:io没有被定义,但是socket.io被加载