Last active
August 29, 2015 14:00
-
-
Save azami/b3940855a50366b095e6 to your computer and use it in GitHub Desktop.
angularjs $httpProviderの設定
This file contains hidden or 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
App.config(['$httpProvider', | |
function($httpProvider) { | |
$httpProvider.defaults.useXDomain = true; | |
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; | |
$httpProvider.interceptors.push('myHttpResponseInterceptor'); | |
$httpProvider.defaults.transformRequest = function(data) { | |
// $resourceを使用する場合はtypeを判定してfunction, objectを除く必要がある。 | |
var params = {}; | |
var i = 0; | |
if (data) { | |
angular.forEach(data, function(value, key) { | |
if (['boolean', 'number', 'string'].indexOf(typeof(data[key])) > 0) { | |
i++; | |
params[key] = value; | |
} | |
}); | |
return i > 0 ? $.param(params) : null; | |
} | |
return data; | |
}; | |
}]); | |
AppServices.factory('myHttpResponseInterceptor', ['$q', '$cookieStore', '$location', function($q, $cookieStore, $location) { | |
return { | |
'request': function(config) { | |
if (! config.url.match(/^views\//)) { | |
config.url = url + config.url; | |
config.params.token = $cookieStore.get('token'); | |
config.headers['Content-Type'] = {'Content-Type': 'application/x-www-form-urlencoded'}; | |
} | |
return config || $q.when(config); | |
}, | |
'response': function(response) { | |
return response || $q.when(response); | |
}, | |
'responseError': function(rejection) { | |
if (rejection.status === 401) { | |
$cookieStore.remove('token'); | |
$location.patn('/401.html'); | |
} | |
return $q.reject(rejection); | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment