Angular $ resource transformRequest不会更改请求标头

时间:2015-11-07 17:54:19

标签: angularjs rest

当我使用$ resource进行REST登录时,transformRequest不会按预期添加Authorization标头。使用$ .ajax调用它可以按预期工作。 所以使用:

    $scope.login2 = function() {
    function setHeader(xhr){xhr.setRequestHeader("Authorization", "Basic " + btoa($scope.gebruikersnaam + ':' + $scope.wachtwoord))}
    $.ajax({type: "POST",  url: "http://localhost:8000/authview/",  beforeSend: setHeader}).
        fail(function(resp){
            console.log('bad credentials.')
        }).
        done(function(resp){
            console.log('welcome ' + resp.email)
        })
}

我在请求中添加了授权标头:

Origin: http://localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36   (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Authorization: Basic YWRtaW46cGFzc3dvcmQ=

但在做的时候:

    $scope.login = function() {
  api.auth.login($scope.getCredentials()).
             $promise.
                 then(function(data){
                     // on good username and password
                     $scope.gebruikersnaam = data.username;
                 }).
                 catch(function(data){
                     // on incorrect username and password
                     alert(data.data.detail);
                 });      
};

其中“api.auth.login”的定义如下:

kmregistratieApp.factory('api', function($resource){
    function add_auth_header(data, headersGetter){
        var headers = headersGetter();
        headers['Authorization'] = ('Basic ' + btoa(data.username + ':' + data.password));
    }
    return {
        auth: $resource('http://localhost:8000/authview/', {}, {
            login: {method: 'POST', transformRequest: add_auth_header},
            logout: {method: 'DELETE'}
        }),
        users: $resource('http://localhost:8000/authview/', {}, {
            create: {method: 'POST'}
        })
    };
});

在“headers ['Authorization'] =('Basic'+ ...”之后(调试时)我可以看到它位于headersGetter中:

headers: Object
Authorization: "Basic YWRtaW46cGFzc3dvcmQ="
accept: "application/json, text/plain, */*"
content-type: "application/json;charset=utf-8"

但在检查标题时,它不会出现在“网络”选项卡中。 所以我的问题是为什么$ resource的工作方式不能添加Authorization标头?

1 个答案:

答案 0 :(得分:2)

TransformRequest不用于修改标头。 见AngularJS changelog。向下滚动一下,你会看到:

  

transformRequest函数不能再修改请求标头。

只能在使用$ http时指定HTTP标头。例如:

$http.post('/someUrl', data, { headers: { 'Authorization': 'Basic'+key } });