【发布时间】:2019-02-06 20:06:34
【问题描述】:
我使用 Dropwizard 编写了一个 REST/JSON API。除了内部单元测试,我一直在使用 Restlet Chrome 扩展和 curl 对其进行测试。 我一直在 HTTP 请求中使用 Content-Type: "application/json" 标头。 这按预期工作。
现在我一直在开发一个基于 JavaScript 的访问 API 的前端。对 JavaScript 没有深入了解,我选择了 JQuery。它适用于 GET 请求。最后一天我一直在努力让 POST 请求正常工作。我不知道我做错了什么。非常感谢您的任何帮助!
关于 API:Dropwizard 资源类如下所示:
@Path("/documents")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DocumentsResource {
//generic stuff happening in the class, including internal data handling and the add() method
@POST
public Response addDocument(@NotNull @Valid TCDocuments documents){
if(documents.getDocuments().length==0){
Response response = Response.status(400).build();
return response;
}
else if(documents.getDocuments().length>0){
for(int i=0; i<documents.getDocuments().length; i++){
TCDocument doc=documents.getDocuments()[i];
add(doc);
}
}
Response response = Response.ok().build();
return response;
}
}
POJO TCDocuments 包含一个 TCDocument POJO 数组。完成的 JSON(在单元测试中用作夹具)是:
{
"documents":[
{
"id":-1,
"label":"My label",
"content":"My content",
"url":""
}]
}
我已经尝试了多种使用 JQuery 发布到它的东西。在我的 HTML 页面中,有一个名为“createF”的表单,我在发布到该界面时使用它来输入数据。如前所述,我不太适合 JavaScript,但按照 StackOverflow 上的建议,我做了以下操作以在 JavaScript 中创建一个文档对象,然后尝试发送它:
var form = $("#createF").serializeArray();
var documents = {
documents: [
{
id: form[0].value,
label: form[1].value,
content: form[2].value,
url: form[3].value
}
]
};
var json = JSON.stringify(documents);
使用我发现的 console.log() 命令,stringify 将 id 放在引号中。这不被我的 API 接受,所以我认为这是发生 415 错误的根源。为了解决这个问题,我使用字符串运算符将一些东西放在一起:
var json = "{ \"documents\":[{\"id\":-1,\"label\":\"metadata json\",\"content\":\"I am ignored\",\"url\":\"\"}]}";
不幸的是,当我尝试使用以下方式发送它时,这也会导致 415 错误: $.post( "../文件", json, 功能(响应){ 控制台.log(resonse); }, “json” );
正如我在这里发现的,我不仅应该将 Content-Type 设置为 HTTP Header,还应该将 Accepted="application/json" 设置为。 POST JSON fails with 415 Unsupported media type, Spring 3 mvc 我不需要在 restlet 客户端或 curl 中指定该标头。但也许 JQuery 的行为不同。我知道什么?于是我写了如下代码:
var url="../documents";
$.postJSON = function(url, json){
return jQuery.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': url,
'data': json,
'dataType': 'json',
'success': function(){
console.log("successfully posted something");
}
});
};
好消息是,这并没有导致 415 消息,但我根本没有收到 API 的回复。网络日志显示,调用该函数时没有包离开浏览器。 我在这里和其他方面发现的所有内容本质上都是关于如何在 JQuery 中使用 $.post 或 $postJSON 的更多信息。我尝试了http://api.jquery.com/jQuery.post/ 的所有示例变体,产生了更多的 415 条消息。
谁能告诉我我做错了什么或者我应该做什么?非常感谢您!
【问题讨论】:
-
您的
Accept': 'application/json'似乎在Accept前面缺少单引号 -
您好@Justin-Pearce,感谢您的评论。将其发布到 stackoverflow 并修复缩进时,这是一个复制粘贴错误。在原始来源中有引号。我更新了我原来的问题。
标签: javascript java jquery json dropwizard