ajax 415
ajax 发送post请求是出现415错误,是ajax的格式有问题,如下。
1 $.ajax({ 2 type: 'POST', 3 url: '/login', 4 data: { 5 "username": username, 6 "password": password 7 }, 8 dataType: "json", 9 success: function(res){ 10 alert(res); 11 } 12 });
更正后:
1 $.ajax({ 2 type: 'POST', 3 url: '/login', 4 data: { 5 "username": username, 6 "password": password 7 }, 8 dataType: "json", 9 contentType:"application/json", 10 success: function(res){ 11 alert(res); 12 } 13 });
就这样改了之后,又来了400错误:
Could not read document: Unrecognized token 'username': was expecting ('true', 'false' or 'null');
当在后台使用@RequestBody来接收参数的时候,就需要在前端中ajax的参数格式为:
1 var json = { 2 "username": username, 3 "password": password 4 } 5 $.ajax({ 6 type: 'POST', 7 url: '/login', 8 data:JSON.stringify(json), 9 dataType: "json", 10 contentType:"application/json", 11 success: function(res){ 12 alert(res); 13 } 14 });
1 @RequestMapping(value="/login", method=RequestMethod.POST) 2 public void login(@RequestBody JSONObject json) 3 { 4 User user = json.getObject("data", User.class); 5 6 // 1、创建 HttpClient 的实例 7 CloseableHttpClient httpClient = HttpClients.createDefault(); 8
要穿原生的格式的ajax的data,也不用在添加@RequestBody的注解了。需要对应着来。
---不要装作很努力