使用ngResource(1.0.6和1.1.4)更改POST请求的Content-Type会遇到麻烦

Trouble changing Content-Type for POST requests with ngResource (1.0.6 and 1.1.4)

本文关键字:请求 POST Content-Type 麻烦 遇到 更改 ngResource 使用      更新时间:2023-09-26

首先,我知道这个问题已经被问过好几次了。我已经尝试了许多张贴的解决方案,没有什么对我有效。

以下是其他一些被问到这个问题的地方:

  • 如何为自定义Angular $resource action指定headers参数
  • 我如何将数据作为表单数据而不是请求有效载荷?
  • 在AngularJS中设置应用范围的HTTP头信息
  • https://groups.google.com/forum/!味精/角度/Mtsf-YdwwWo/P_Ui4t_DiXkJ

尝试:

var app = angular.module('theApp', ['app.services']);

app
  .config(['$httpProvider', function ($httpProvider) {
    // Try (1): This doesn't work
    $httpProvider.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8';
    // Try (2): This doesn't work either
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
  }])

angular.module('app.services', ['ngResource'])
  // Resource for Drupal system/connect.post API (via services.module)
  .factory('SystemConnect', function($resource, $http) {
    // Try (3): There's no way this should work. But what the hell let's try!
    $http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8';
    $http.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
    return $resource('api/system/connect.json', {}, {
      post: {
        method: 'POST',
        params: { },
        isArray: true,
        // Try (4): This doesn't work either
        headers: { 'Content-Type': 'application/json;charset=utf-8' }
      }
    });
  });

function SomeCtrl($scope, SystemConnect) {
  // FAIL, this results in "406 Not Acceptable: Unsupported content type application/xml"
  $scope.user = SystemConnect.post();
}
app.controller('SomeCtrl', SomeCtrl);

听起来很多人以前都解决过这个问题。有人能告诉我正确的方法吗?

PS:奇怪的是,当在Firefox中运行这段代码时,Angular使用'Content-Type: text/plain'作为POST!?

我记得读到过你必须在帖子中包含内容才能接受你的标题更改。

$scope.user = SystemConnect.post({});