我正在做AngularJS的一个项目。我在angularjs中使用$http.post发布了'form data‘类型的数据。但它显示一个错误:"415不支持的媒体类型“
angular.module('odeskApp')
.factory('Password', function ($http, $q) {
return {
update: function (pwd) {
var deferred = $q.defer();
$http.post('/api/user/password', { 'password': pwd }, {
headers: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
},
transformRequest: function(data) { // If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) +
"=" +
encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer
.join( "&" )
.replace( /%20/g, "+" )
;
return( source ); }
})
.success(function (data) {alert("success");
$('#changePasswordAlert .alert-success').show();
$('#changePasswordAlert .alert-danger').hide();
$('#changePasswordAlert .alert').mouseout(function(){ $(this).fadeOut('slow'); });
deferred.resolve(data); //resolve data
})
.error(function (err) {
$('#changePasswordAlert .alert-danger').show();
$('#changePasswordAlert .alert-success').hide();
deferred.reject();
$('#changePasswordAlert .alert').mouseout(function(){ $(this).fadeOut('slow'); });
});
return deferred.promise;
}
};
}); 我不知道这里发生了什么。我还定义了头文件。请建议任何可能的解决方案或请让我知道,如果需要任何额外的信息。
发布于 2014-11-25 19:42:07
问题可能是因为您将Content-Type指定为'application/x-www-form-urlencoded; charset=UTF-8',但发送的数据是JSON对象。将其更改为:
Content-Type: 'application/json'这应该可以修复错误。
https://stackoverflow.com/questions/24079802
复制相似问题