简体   繁体   English

AngularJS $ resource save()导致HTTP错误415(不支持的媒体类型)

[英]AngularJS $resource save() causes HTTP Error 415 (Unsupported Media Type)

I am using Angular 1.2-RC2 (also tried 1.0.8 and 1.1.x) and the ngResource module. 我正在使用Angular 1.2-RC2(也尝试过1.0.8和1.1.x)和ngResource模块。 The backend is a Spring WebMVC application. 后端是Spring WebMVC应用程序。

angular.module("dox", ['ngResource'])

.controller('SettingsController', function ($scope, Settings) {
    $scope.settings = Settings.query();

    $scope.save = function () {
        Settings.save();
    };
})

.factory('Settings', function ($resource) {
    return $resource('/api/v1/settings/:settingId', {settingId: '@id'}, {
        'save': {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        }
    });
});

Whenever the save() method on the Settings class gets called the frontend receives a HTTP 415 (Unsupported media type). 每当调用Settings类上的save()方法时,前端都会收到HTTP 415(不支持的媒体类型)。 The reason is that AngularJS send the POST request using the following content type: 原因是AngularJS使用以下内容类型发送POST请求:

Content type: text/plain;charset=UTF-8

but the backend expects 但是后端期望

Content type: application/json;charset=UTF-8

According the API docs it should be possible to override the header but my settings are somehow ignored. 根据API文档 ,应该可以覆盖标头,但是以某种方式忽略了我的设置。 I seems that this is a common problem and as a workaround there are many recommendation to use $http.post instead of $resource. 我似乎这是一个常见问题,作为一种解决方法 ,有许多建议使用$ http.post代替$ resource。

Can you give me any hint how to solve this content type problem using the $resource service? 您能给我些提示如何使用$ resource服务解决此内容类型问题吗?

Please find the backend controller code here . 请在此处找到后端控制器代码。

First, you're overriding a built-in $save method, so you can just omit the save: part (see source code ). 首先,您将重写内置的$save方法,因此您可以省略save:部分(请参阅源代码 )。 If you do define additional HTTP methods that aren't built-in, you can update the $httpProvider like so (this is to add the patch method): 如果您确实定义了其他非内置的HTTP方法,则可以像这样更新$httpProvider (这是添加patch方法):

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.patch = {
         'Content-Type': 'application/json;charset=utf-8'
    }
}]);

Kevin Stone pushed me to the right direction. 凯文·斯通将我推向正确的方向。 Thank you! 谢谢!

Since query() returns an array and save() is meant to save only one item of that array at the same time I had to reimplement the save() stuff differently . 由于查询()返回一个数组,并保存()是指在同一时间,我不得不重新实现节约()的东西只保存一个数组的项目不同

$scope.save = function () {    
   angular.forEach($scope.settings, function (value, key) {                    
      value.$save();
   });
};

Done! 做完了! Again thank you for your hints and help 再次感谢您的提示和帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM