【问题标题】:Getting error "415 Unsupported Media Type" while posting data in angularJS在 angularJS 中发布数据时出现错误“415 Unsupported Media Type”
【发布时间】:2014-11-25 19:42:06
【问题描述】:

我正在开发一个 AngularJS 项目。我在 angularjs 中使用 $http.post 以“表单数据”类型发布数据。 但它显示错误:“415 Unsupported Media Type”

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; 
        }
    };
});  

我不知道这里会发生什么。我也定义了标题。请提出任何可能的解决方案,或者如果需要任何额外信息,请告诉我。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    问题可能是因为您将Content-Type 指定为'application/x-www-form-urlencoded; charset=UTF-8',但您发送的数据是一个JSON 对象。因此,服务器正在接收与预期不同的内容。将其更改为:

    Content-Type: 'application/json'
    

    这应该可以解决错误。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      相关资源
      最近更新 更多