在标头上设置令牌默认

在标头上设置令牌默认

本文介绍了Angular Js-在标头上设置令牌默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向每个API调用添加带有访问令牌的标头.它适用于所有GET请求,但是一旦我尝试进行POST,便不会添加标头.

Im trying to add a header with my access token to each API call. It works well for all the GET requests, but as soon as I try to make a POST the header isn't added.

这是我添加令牌的方式:

Here is how I add the token:

app.factory('api', function ($http, $cookies) {
return {
    init: function (token) {
        $http.defaults.headers.common['Token'] = token || $cookies.loginTokenCookie;
    }
  };
});

从这里打来的电话

app.run(function ($cookies, $http, $location, $rootScope,api) {
    $rootScope.location = $location;
    api.init();
});

我尝试过如下操作:

app.factory('api', function ($http, $cookies) {
return {
    init: function (token) {
        $http.defaults.headers.common['Token'] = token || $cookies.loginTokenCookie;
        $http.defaults.headers.post['Token'] = token || $cookies.loginTokenCookie;

    }
};
});

但这也不起作用.仅当我更改标题键名称时,它才起作用,如下所示:

But this also doesnt work. It only works when I change the header key name like the following:

 $http.defaults.headers.post['Token-Post'] = token || $cookies.loginTokenCookie;

如何为AngularJs中的帖子分配默认标题并获取请求?

How do I assign a default header to posts and get requests in AngularJs?

推荐答案

与其将令牌放在每个服务(或调用)内部的标头上,不如使用$http拦截器().

Instead of placing the token on the headers inside each service (or call), it might be better to use an $http interceptor (docs here).

然后,您可以将令牌放置在每个请求上.无论请求是GET还是POST,这都将起作用.

Then, you can place the token on every request. This will work whether the request is a GET or POST.

JS示例:

$httpProvider.interceptors.push(function($q, $cookies) {
    return {
     'request': function(config) {

          config.headers['Token'] = $cookies.loginTokenCookie;
          return config;
      }
    };
  });

这篇关于Angular Js-在标头上设置令牌默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:06