首页 > 解决方案 > 如何从客户端发送 JavaScript 对象以及如何在 Spring Boot 后端接收和解析它们?

问题描述

我在尝试制作我的网络应用程序时多次来过这个问题并且已经厌倦了没有结果,以至于我不得不在这里问,所以如果我发泄出来,请原谅我......我是相当加重。

我正在尝试以键值对的形式从我的客户端(vanilla js)发送到我的后端(spring boot java)。我已经尝试了很多方法,但似乎找不到正确的方法/组合来实现我想要做的事情。我当前的非工作代码如下。

客户端 JS

var object = {
        'id' : 1,
        'username' : 'jumpthruhoops',
        'password' : 'melodysteez'
    };

    Axios
        .post('http://localhost:8080/gameSchedule', JSON.stringify(object))
        .then((response) => {
            console.log(response.data);
        });

后端 Spring Boot/Java

@CrossOrigin
@RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(@RequestBody String user) {
    System.out.println(user);
    return "test";
}

以下代码是我目前拥有的,它给了我任何接近我正在寻找的结果。它给了我以下印刷线......

%7B%22id%22%3A1%2C%22username%22%3A%22tdellard1%22%2C%22password%22%3A%22sisters3%22%7D=

...我相信这是我传递给参数的字符串对象的十六进制代码。我不确定这是否来自 Spring Boot,或者这是否是 JSON.stringify 所做的。由于用户对象是一个测试对象,而我计划传入的实际对象要复杂得多,所以我不想弄清楚如何解码十六进制代码,除非我无法进行任何其他操作并且我完全必须。

因为比较复杂,我不想在方法的参数中使用很多@RequestParams("name") String VaribleName之类的40次。这也是获得结果的唯一其他方法,但将这些变量传递到 url 令人抓狂。

我尝试过的其他一些事情是@ModelAttribute 和(@RequestBody User user),它们都返回错误,一个似乎再次发生的错误是

018-10-30 23:38:29.346 WARN 12688 --- [io-8080-exec-10] .wsmsDefaultHandlerExceptionResolver: 已解决 [org.springframework.web.HttpMediaTypeNotSupportedException: 内容类型 'application/x-www-form-urlencoded; charset=UTF-8' 不支持]

所以我非常想知道从 Axios(form.serialize、JSON.stringify、JavaScript 对象等)发送数据的最佳方式是什么,以及我需要使用什么相应的方法来获取该数据我的 Spring Boot 后端并使其具有操作性,以便我可以将其变成 POJO。

标签: javascriptjavajsonspring-bootaxios

解决方案


只需删除 JSON.stringify(object) 并放置对象。

Axios
    .post('http://localhost:8080/gameSchedule', object)
    .then((response) => {
        console.log(response.data);
    });

您可以在axios 文档中看到有关 POST 请求的示例

在 Spring Boot 上,您必须创建一个像这样的实体:

@Entity
public class UserAccount implements Serializable {

@Id
private Long id;

@Column(unique = true, nullable = false)
@Size(max = 255)
private String userName;

@Column(nullable = false)
@NotNull
private String password;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

并在此处更改您的代码

@CrossOrigin
@RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserAccount getSchedule(@RequestBody UserAccount user) {
    System.out.println(user.getUserName());
    return user;
}

推荐阅读