前端传json数据给后台报415错误
1, 报错信息
前端Ajax请求代码如下
$.ajax({
url:'/userinfo',
type:'POST',
data:JSON.stringify(list),
dataType:'json',
success:function (data) {
alert("注册成功");
},
error:function (data) {
alert("注册失败"+data);
}
});
2,解决办法:Ajax语句添加 contentType:‘application/json’,
$.ajax({
url:'/userinfo',
type:'POST',
data:JSON.stringify(list),
dataType:'json',
contentType:'application/json',
success:function (data) {
alert("注册成功");
},
error:function (data) {
alert("注册失败"+data);
}
});
3、出错原因
4开头的错误为:请求错误
415 Unsupported Media Type
对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝。
对于jQuery的Ajax请求:
contentType 主要设置你发送给服务器的格式,contentType默认的值:application/x-www-form-urlencoded,dataType设置你收到服务器数据的格式。
出错原因是后台要求接收的数据为application/json。