Last active
February 28, 2016 07:09
-
-
Save sscovil/3bd0da1d98397213df54 to your computer and use it in GitHub Desktop.
AngularJS: Preserve Content-Type header with Restangular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
angular.module('myApp', ['restangular']) | |
.config(httpConfig) | |
; | |
function httpConfig($httpProvider) { | |
$httpProvider.interceptors.unshift(interceptor); // use unshift to run before Restangular's interceptor | |
function interceptor() { | |
return { | |
request : requestInterceptor | |
}; | |
function requestInterceptor(config) { | |
if (angular.isDefined(config.headers['Content-Type']) && !angular.isDefined(config.data)) | |
config.data = ''; | |
return config; | |
} | |
} | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
angular.module('myApp', ['restangular']) | |
.config(restangularConfig) | |
; | |
function restangularConfig(RestangularProvider) { | |
RestangularProvider | |
.addFullRequestInterceptor(preserveContentTypeHeader) | |
; | |
function preserveContentTypeHeader(element, operation, route, url, headers, params, httpConfig) { | |
if (angular.isDefined(headers['Content-Type']) && !angular.isDefined(httpConfig.data)) | |
httpConfig.data = ''; | |
} | |
} | |
})(); |
Do you really need Restangular over $http? It would seem like such a common task for Angular to have to send Content-Type headers. What does Restangular have that $http doesnt?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The AngularJS
$http
service strips theContent-Type
header from any request that does not havedata
defined in its config (see this question on StackOverflow). This is an example of how to solve the problem when using Restangular instead of $http.