在使用axios和springmvc做一个前后端分离的小项目时,遇到,springmvc响应回的数据是json格式,但在vue脚手架解析时却变成了string
this.$http.post("login", this.loginForm,{ emulateJSON:true,responseType:'json'}).then((response) => {
//这里不转换的话会变成字符串,其他方法暂时不知道
var res=JSON.parse(response.data);
alert(typeof response.data);//这里显示为string类型
if (res.flag) {
this.$message.success("登录成功");
this.$router.push({ path: "/home" });
//存储user对象
window.sessionStorage.setItem("user",res.user)
} else {
this.$message.error("登录失败");
}
});
后端java代码:
```java
@Autowired
private UserService userService;
@RequestMapping(value = "/login",produces = "application/json;charset=UTF-8")
@ResponseBody
public String login(@RequestBody User loginUser){
System.out.println(loginUser);
User user = userService.login(loginUser);
HashMap<String, Object> res = new HashMap<String, Object>();
boolean flag=false;
if (user != null) {
flag=true;
}
res.put("flag",flag);
res.put("user",user);
String resJson= JSON.toJSONString(res);
System.out.println(resJson);
return resJson;
}