2015-11-07 42 views
0

当我使用$资源进行REST登录时,transformRequest不会按预期方式添加授权标头。使用$ .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'} 
     }) 
    }; 
}); 

“头[‘授权’] =(‘基本’+ ...”(调试时),我可以看到它坐在headersGetter后:

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

但它不会在网络选项卡时打开了检查标题。 所以我的问题是为什么$资源的工作方式没有添加授权标题?

回答

2

TransformRequest并不打算用于修改标题。 见AngularJS changelog。向下滚动,您将看到:

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

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

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

据我所见,这个改变是为了$ http。 $ resource [link](https://docs.angularjs.org/api/ngResource/service/$resource)的角度文档明确指出:转换函数采用http请求正文和标头......但如果此更改已对$资源的影响也是如此,这将解释我认为的行为(也许文档应该改变它) – majodi