如何从客户端发送JavaScript对象以及如何在Spring Boot后端中接收和解析它们?

时间:2018-10-31 04:46:22

标签: javascript java json spring-boot axios

在尝试制作我的Web应用程序时,我来了无数次此问题,并且对结果一无所获感到厌倦,以至于我不得不在这里问一下,所以请原谅我发泄。我很生气。

我正在尝试将键值对形式的数据从客户端(香草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”)字符串VaribleName,例如40次。这也是获得结果的唯一其他方法,但是将这些变量传递给url令人发疯。

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

  

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

所以我要问的是关于从Axios发送数据的最佳方法(form.serialize,JSON.stringify,JavaScript Object等)的指导,以及我需要使用哪种相应的方法来获取指导该数据在我的Spring Boot后端上进行处理,以便将其转换为POJO。

2 个答案:

答案 0 :(得分:0)

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

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

您可以在axios documentation

上看到有关POST请求的示例

在Spring启动时,您必须创建一个像这样的实体:

@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;
}

答案 1 :(得分:0)

如果要发送对象,则在后端接收时必须使用对象,并确保请求对象中的字段名称和后端的类的字段名称必须相同, 所以应该是这样的:

我只是在您的代码中进行一些更改以访问字段:

var data = {  
        'id' : 1,
        'username' : 'jumpthruhoops',
        'password' : 'melodysteez'
    };
// name of variable(data variable) doesn't matter but inside everything consider as a body

axios.post('http://localhost:8080/gameSchedule', JSON.stringify(object), {
        headers: {
            'Content-Type': 'application/json',
        }
    }
    );

后端检索字段

//create one Student class to map fields with body 

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