最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

特定端点的角度设置标头角度为1

运维笔记admin9浏览0评论

特定端点的角度设置标头角度为1

特定端点的角度设置标头角度为1

我环顾四周但找不到对我有用的东西。我有2个端点,一个用于后端,我可以访问,另一个用于外部服务。

在我的.run我有一个拦截器,将此标头添加到我的服务器$http.defaults.headersmon['Authorization'] = 'JWT' + ' ' token'; 的每个请求

为外部api服务。

 service('CorsRequest', function ($http) {

            var baseUrl = '/';

            this.get = function (endpoint) {
                return $http.get(baseUrl + endpoint, { headers: {"Content-Type": 'text/plain'}});

            }

            this.post = function (endpoint, postData) {
                return $http.post(baseUrl + endpoint, postData);
            }
        })

当向该api发出请求时,第二个端点返回一个预检错误,因为这个Authorization头被添加到它。

如何检查请求是否发送到我的服务器,添加Authorization标头,如果不忽略。

回答如下:

这是我用Slava建议用http拦截器修复的方法。

为它创建了一个工厂,并使用注入器获取我创建的服务以使用它。

  .factory('ApiInterceptor', function($localStorage, $injector){

    console.log('here')
    return {
       request: function(config) {

      var UserService = $injector.get('UserService');

      if(config.url.indexOf(BASE_URL) > -1) {
        config.headers['Authorization'] = 'JWT' + ' ' + UserService.getCurrentUserToken() ;

      }
      // console.log(config)
      return config;
    },
      response: function(response) {
          // console.log(response.data);
          return response;
        }
    }

})

然后添加了配置。

.config(function($httpProvider) {       
    $httpProvider.interceptors.push('ApiInterceptor');
  })
发布评论

评论列表(0)

  1. 暂无评论