Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs + interceptors + add query parameters for only http request( not html,js,css files)

I am using angularjs, In backend I check every api authenticated. Every request should be checked the parameter access_token.

$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
    return {
        request : function(config) {
            config.params = config.params || {};
            if ($localStorage.access_token) {
                config.params.access_token = $localStorage.access_token;
            }
            return config || $q.when(config);
        },
    };
});

// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor'); 

I using this code. Its working good, but I saw in development tools(Network) the html, css, js files also added the parameters. like.

http://localhost/webapp/views/template/left-menu.html?access_token=xxxxxxxxxxxxxxxxx
http://localhost/webapp/css/index.css?access_token=xxxxxxxxxxxxxxxxx

But I don't like to send access_token to all http request(html,css,js).

I like to send the access_token for what are have prefix api

http://localhost:9090/api/user/get?access_token=xxxxxxxxxxxxxxxxxxxxxx

//I think the solution is find the http url and grep the text api, if found means add the parameter. Don't konw this is good approach.

Please me the good approach.

I expect only backend api request only. Also I don't expect every serive http request to add parameter.

Its possible to add common one place in config ?

like image 572
RSKMR Avatar asked Feb 07 '23 20:02

RSKMR


1 Answers

You can check url:

$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
return {
    request : function(config) {
        var apiPattern = /\/api\//;

        config.params = config.params || {};

        if ($localStorage.access_token && apiPattern.test(config.url)) {
            config.params.access_token = $localStorage.access_token;
        }
        return config || $q.when(config);
    }
  };
});
// Add the interceptor to the $httpProvider.

$httpProvider.interceptors.push('MyHttpInterceptor');
like image 145
Anton Kirzyk Avatar answered Feb 09 '23 10:02

Anton Kirzyk