首页 > 解决方案 > 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从服务器端方法中删除测试,那么调用工作正常。它只是

标签: javajqueryajaxspringpost

解决方案


这里的问题

@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.

参见权威示例:https ://spring.io/guides/tutorials/rest/


推荐阅读