首先,我知道这个问题已经被问过好几次了。我尝试了许多已发布的解决方案,但没有什么对我有用..
这是被问到的其他几个地方:
- 如何为自定义 Angular $resource 操作指定 headers 参数
- 如何将数据作为表单数据而不是请求有效负载发布?
- 在 AngularJS 中设置应用程序范围的 HTTP 标头
- https://groups.google.com/forum/#!msg/angular/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!?