I have following jquery
<script>
var response = '';
$.ajax({ type: "POST",
url: "http://localhost:8080/hsv06/checkUserExists",
async: false,
data: "title=foo",
success : function(text)
{
response = text;
}
});
console.log(response);
</script>
And here is the rest controller:
@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json")
public @ResponseBody boolean checkUser(@RequestBody Object title){
System.out.println(title);
return true;
}
However this produces the following error:
POST http://localhost:8080/hsv06/checkUserExists 415 (Unsupported Media Type)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ (index):57
What is the problem? What is wrong with the way I am sending the data?
415 means unsupported media type. Your server consumes application/json, so you client must provide application/json data. To fix it, just add the type to your jquery like the following.
$.ajax({ type: "POST",
url: "http://localhost:8080/hsv06/checkUserExists",
async: false,
data: JSON.stringify({title: "food"}),
// specifying data type
contentType: "application/json; charset=utf-8",
success : function(text)
{
response = text;
}
});
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8"
Your Spring REST backend should be like the following. Since the post data is {title: "food"}, Spring will parse it into a Map.
@RequestMapping(value="/checkUserExists", method=RequestMethod.POST, consumes="application/json")
public @ResponseBody boolean checkUser(@RequestBody Map<String, String> param){
System.out.println(param);
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.