如何在AngularJS上设置$ http标头?

时间:2015-11-12 04:05:37

标签: angularjs

我正在尝试为$ http创建基本身份验证,为此我正在尝试设置标头,但我不能这样做。

我怎么能这样做?

尝试这个。

var app = angular.module("starter");

app.service("UserLoginAPI", function($http, AppConstants, Base64){
    this.doLogin = function(){
        var _url = AppConstants.webServiceUrl + "/users/testaWS.json";
        var _authdata = Base64.encode('admin' + ':' + 'admin');

        var _condigHeader = {
            headers: {
                'Authorization': 'Basic ' + _authdata,
                'Accept': 'application/json; charset=utf-8',
                'Content-Type': 'application/json; charset=utf-8'               
            }
        };

        return $http.post(_url, _condigHeader);         

    };
});

异常

OPTIONS http://192.168.1.105/GuairaFoods/users/testaWS.json (anonymous function) @ ionic.bundle.js:19346sendReq @ ionic.bundle.js:19165serverRequest @ ionic.bundle.js:18877processQueue @ ionic.bundle.js:23399(anonymous function) @ ionic.bundle.js:23415Scope.$eval @ ionic.bundle.js:24678Scope.$digest @ ionic.bundle.js:24489Scope.$apply @ ionic.bundle.js:24783(anonymous function) @ ionic.bundle.js:57605eventHandler @ ionic.bundle.js:12103triggerMouseEvent @ ionic.bundle.js:2870tapClick @ ionic.bundle.js:2859tapMouseUp @ ionic.bundle.js:2932
(index):1 XMLHttpRequest cannot load http://192.168.1.105/GuairaFoods/users/testaWS.json. Response for preflight has invalid HTTP status code 401
VM455:3 XHR Loaded (testaWS.json - 401 Unauthorized - 330.49999992363155ms - 0B)

2 个答案:

答案 0 :(得分:0)

不要将headers对象包装在_condigHeader对象中。

 var headers = {
                'Authorization': 'Basic ' + _authdata,
                'Accept': 'application/json; charset=utf-8',
                'Content-Type': 'application/json; charset=utf-8'               
            }

        return $http.post(_url, headers); 

答案 1 :(得分:0)

解决了这个问题。

我做了。

var app = angular.module("starter");

app.service("UserLoginAPI", function($http, AppConstants, Base64){
    this.doLogin = function(){
        var _url = AppConstants.webServiceUrl + "/users/testaWS.json?callback=JSON_CALLBACK";
        var _authdata = Base64.encode('admin' + ':' + 'admin');

        var _headers = {
                'Authorization': 'Basic ' + _authdata,
                'Accept': 'application/json; charset=utf-8',
                'Content-Type': 'application/json; charset=utf-8'               
            };

        return $http({
                method: 'jsonp',
                url: _url,
                responseType: "json",
                headers: _headers
                });
    };
});

我必须更改我的webservice中的函数才能获得jsonp的回调。

public function testaWS(){            
            $this->autoRender = false;             
            $retorno = array("data"=>"ok");
            return $_GET['callback'] . '('.json_encode($retorno).')';            
        }