加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 外部网址的Http拦截器

发布时间:2020-12-17 10:22:21 所属栏目:安全 来源:网络整理
导读:我编写了一个http拦截器来为每个请求添加身份验证令牌.在我的html中,当我点击链接时,不会调用此拦截器.不确定为什么会这样? 我的拦截器代码 – angular.module('demo',[]).factory('httpAuthorizationInterceptor',['$window',function ($window) { return
我编写了一个http拦截器来为每个请求添加身份验证令牌.在我的html中,当我点击链接时,不会调用此拦截器.不确定为什么会这样?

我的拦截器代码 –

angular.module('demo',[])
.factory('httpAuthorizationInterceptor',['$window',function ($window) {
    return {
        request: function (config) {
            if (config.url.indexOf('login') == -1) {
                config.headers['Authorization'] = 'Session ' +<session_id>;
            }
            return config || $q.when(config);
        }
    };
}])

我的HTML –

<a data-ng-href="http://example.com/view"></a>
你的锚标签实际上不会进行ajax调用,http拦截器用于拦截通过angular进行的ajax调用.单击该锚标记就像在浏览器中打开URL一样.

为了执行ajax调用:您需要以下列方式调整代码:

angular.module('demo',[])
.config(['$httpProvider',function ($httpProvider) {

    var interceptor = [function() {
        return {
            'request': function(config) {
                if (config.url.indexOf('login') == -1) {
                    config.headers['Authorization'] = 'Session ' + <session_id>;
                }
                return config;
            }
        };
    }];

    $httpProvider.interceptors.push(interceptor);
}]);

现在您的控制器代码看起来像是:

$scope.doSomething = function() {
    $http({method: 'GET',url: 'http://example.com/view'}).then(function(data) {
        // success
    });
};

您的HTML代码将是:

<a href="doSomething()"></a>

唯一的问题是,您正在进行ajax调用的外部URL要么位于同一域,要么必须支持跨源请求.

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读