I am using Vue.js, axios and Spring.
On the page I have the following axios code
axios({
method: 'post',
url: '/user/info',
params: {
'_csrf' : document.getElementById('csrf_id').value,
'name' : 'job',
'age' : '25',
},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
And on the server I have a receiving method like this
@Controller
@RequestMapping("/user")
public class UserInfo {
@ResponseBody
@PostMapping(value = "/info", consumes = "application/x-www-form-urlencoded", produces = "application/json" ";charset=utf8")
public String info(@RequestParam(value = "name") String name, @RequestParam(value = "age") String age) {
System.out.println(name);
System.out.println(age);
return "ok";
}
}
Axios makes a request to the server, but the server returns a 415 response. The request headers are missing the application/x-www-form-urlencoded content type. I suspect the problem lies precisely in this.
Tell me, what am I doing wrong?
CodePudding user response:
HttpMethod Post is a method of writing and transmitting data in the request body.
In your case, you put data through params
. If you execute code as you write, data will be sent such as /user/info?_csrf=value&name=job&age=25
and there will be no data in the request body.
To get the response you want, you can modify it as below.
axios({
method: 'post',
url: '/user/info',
data: '_csrf=csrf&name=job&age=25',
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
change params
keyword to data
and write data like querystring.