Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在AngularJS中的每个$http之前获取api令牌_Angularjs_Laravel - Fatal编程技术网

在AngularJS中的每个$http之前获取api令牌

在AngularJS中的每个$http之前获取api令牌,angularjs,laravel,Angularjs,Laravel,在我的应用程序和http post中使用AngularJS,服务器需要一个令牌,我们可以通过http get获得该令牌。但是我想在每次http调用之前运行token\u generate()函数,因为有时候令牌会过期 token = function() { var api = AuthService.getToken(); api.success(function (response) { var token = response.token;

在我的应用程序和http post中使用AngularJS,服务器需要一个令牌,我们可以通过http get获得该令牌。但是我想在每次http调用之前运行
token\u generate()
函数,因为有时候令牌会过期

token = function() {
    var api = AuthService.getToken();
    api.success(function (response) {
        var token = response.token;
        $http.defaults.headers.common['X-CSRF-TOKEN'] = token;
    });
};
token();

您需要注册一个$http侦听器:

(功能(窗口、角度){
函数tokenizerConfig($httpProvider){
函数注册侦听器($q、$http、AuthenticationService){
var拦截器={};
interceptors.request=函数(配置){
if(AuthenticationService.isTokenValid){
返回$q.when(配置);
}
var qs={};
返回$http
.get(令牌_API,{cache:false,params:qs})
.然后(函数(结果){
AuthenticationService.setToken(result.data.token);
返回配置;
})
;
};
返回拦截器;
}
$httpProvider.interceptors.push(['$q','$http','AuthenticationService',registerInterceptors]);
}
有棱角的
.module('tokenizer',[])
.config(['$httpProvider',tokenizerConfig])

})(窗户,窗户,有棱角)创建Ajax服务并使用该服务发送所有Ajax调用,现在您可以发送get令牌调用,然后发送任何Ajax调用,您可以考虑使用拦截器并将其与$httpPosial.拦截器挂钩,并在每个HTTP请求之前获取新令牌。