对简单POST请求的错误请求

时间:2019-08-28 14:26:17

标签: rest spring-boot post

我已经将其分解为最低限度,但仍然不知道为什么会这样。 我的控制器中有以下方法:

@RequestMapping(method = RequestMethod.POST, value = "/myGreatCall")
public String getDynamicData(@RequestBody DataRequest dr) {
    return dr.toString();
}

使用以下简单的类:

public class DataRequest {
    private String type;
    //Getters and setters here
}

现在,如果我尝试调用它,则会收到错误400作为响应。

let url = window.location.protocol+"//"+window.location.host+"/myGreatCall";

    let request = new XMLHttpRequest();
    request.open("POST", url, true);

    request.onload = function () {
        console.log(request.response); //Here I read the reponse and get the error 404
    };

    // This is the data I send as the body
    let data = JSON.stringify(
        {
            type: "myType"
        }
    );


    request.setRequestHeader("Content-Type", "application/json");
    request.send(data);

现在从错误中我怀疑由于某种原因它无法将json对象映射到java对象中,但是我不知道为什么。

我测试了以下内容:

  • 在没有方法参数的情况下执行请求,
  • java类中的不同数据类型
  • 将硬编码字符串'{\“ type \”:\“ myType \”}“移交给#send()

有什么想法我可能做错了吗?

2 个答案:

答案 0 :(得分:0)

可能取决于JSON序列化。试试这个:

let data = JSON.stringify(
        {
            "type": "myType"
        }
    );

答案 1 :(得分:0)

好吧,似乎有些奇怪。我不知道是什么原因造成的,但是在PC重新启动后,它工作正常。