尝试在前端使用Vue3单面中使用axios向后端Post json数据时,参数老是没有传过去。前端程序如下:
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios
.post(url, {name:"test"})
.then(response=>this.message=response)
.catch(function(error){
this.message=error;
});
Java后端程序如下:
@RequestMapping(value="/VuePostTest")
public String vuePostTest(@RequestBody String json) {
try {
System.out.println(json);
return "ok";
}catch(Exception ex) {
return "error";
}
}
结果都没有接收到预期的参数,查了一下网上的资料,需要显示指定Content-Type,服务端程序修改为:
@RequestMapping(value="/VuePostTest", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
public String vuePostTest(@RequestBody String json) {
try {
System.out.println(json);
return "ok";
}catch(Exception ex) {
return "error";
}
}
php服务端程序接收json方式的post的程序:
$jsonPost = json_decode(file_get_contents('php://input'), true);