为了账号安全,请及时绑定邮箱和手机立即绑定

为一个请求设置HTTP标头

为一个请求设置HTTP标头

RISEBY 2019-08-30 17:05:30
我的应用程序中有一个特殊请求需要基本身份验证,因此我需要为该请求设置Authorization标头。我读到了有关设置HTTP请求标头的内容,但据我所知,它将为该方法的所有请求设置该标头。我的代码中有类似的东西:$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";但我不希望我的每个帖子请求发送此标头。有没有办法只为我想要的一个请求发送标题?或者我是否必须在我的要求后将其删除?
查看完整描述

2 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

试试这个,也许它有效;)


.factory('authInterceptor', function($location, $q, $window) {



return {

    request: function(config) {

      config.headers = config.headers || {};


      config.headers.Authorization = 'xxxx-xxxx';


      return config;

    }

  };

})


.config(function($httpProvider) {

  $httpProvider.interceptors.push('authInterceptor');

})

并确保你的后端也工作,试试这个。我正在使用RESTful CodeIgniter。


class App extends REST_Controller {

    var $authorization = null;


    public function __construct()

    {

        parent::__construct();

        header('Access-Control-Allow-Origin: *');

        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");

        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {

            die();

        }


        if(!$this->input->get_request_header('Authorization')){

            $this->response(null, 400);    

        }


        $this->authorization = $this->input->get_request_header('Authorization');

    }


}


查看完整回答
反对 回复 2019-08-30
  • 2 回答
  • 0 关注
  • 769 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信