java - Spring RestAPI 的 AJAX POST 方法不起作用
问题描述
我正在尝试使用 jQuery AJAX 将大量数据发送到我的服务器端,并将其发送到 Spring Framework 中的 RESTful 服务。并且形式为未知大小的数组,所以我试图让自动序列化工作。但我什至无法让它与一个简单的测试示例一起工作。
似乎无法将我的 JSON 文件与输入类匹配。所以我一定做错了什么。但是根据我一直在尝试遵循的教程,我无法看到我做错了什么。
这是我的 AJAX 调用
var test = JSON.stringify({
name : "hallo", lastname : "there"
});
console.log(test);
$.ajax({
type: "POST",
url: "/SpringTest_war_exploded/test",
contentType: "application/json",
data: test,
success: function (returnValue) {
console.log("success");
console.log(returnValue);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log (XMLHttpRequest);
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
这是我的服务器端方法。
@PostMapping(value = "/test", consumes = "application/json")
@ResponseBody
public String testajax(@RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
这是我要与之匹配的课程
public class TestAutoCreate {
private String name;
private String lastname;
public TestAutoCreate(String name, String lastname) {
this.name = name;
this.lastname = lastname;
}
// the getters and setters
...
}
这是我得到的错误消息
The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
如果我@RequestBody TestAutoCreate
从服务器端方法中删除测试,那么调用工作正常。它只是
解决方案
这里的问题
@PostMapping(value = "/test", consumes = "application/json")
@ResponseBody
public String testajax(@RequestBody TestAutoCreate test){
System.out.println("testajax");
System.out.println(test.getName());
return "hallo";
}
它是 RESTful 控制器,但返回视图。您必须返回 RESTful 响应,内容类型为Content-Type: application/json
.
推荐阅读
- azure-devops - 报告:Azure DevOps Pipelines
- postgresql - PostgreSQL 从日期变量中提取年份
- iframe - 如何在 keycloak 的 iframe 中打开管理帐户页面
- java - 在 Java 中创建监听器
- javascript - 使用 Context API 时访问全局状态
- django-cms - 如何从 DjangoCMS 菜单中排除未发布的页面?
- java - 无法自动接线。找不到“AuthenticationProvider”类型的 bean
- javascript - 根据数组中的值将数据从一个数组添加到另一个数组的最佳方法是什么?
- java - 如何在Java中根据开始和结束文本分割文本
- java - PMD 问题为空指针异常