Skip to content

Instantly share code, notes, and snippets.

@sscovil
Last active February 28, 2016 07:09
Show Gist options
  • Save sscovil/3bd0da1d98397213df54 to your computer and use it in GitHub Desktop.
Save sscovil/3bd0da1d98397213df54 to your computer and use it in GitHub Desktop.
AngularJS: Preserve Content-Type header with Restangular
(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;
}
}
}
});
(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 = '';
}
}
})();
@sscovil
Copy link
Author

sscovil commented Sep 11, 2015

The AngularJS $http service strips the Content-Type header from any request that does not have data 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.

@alxvallejo
Copy link

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