2013-01-06 44 views

回答

39
$http.defaults.headers.common['Auth-Token'] = 'token'; 

看起來headers()規範化了鍵名。

+3

你能詳細說明你的意思嗎?規範化的關鍵名稱? – Webnet

+4

使用headers()方法獲取標題時,「Auth-Token」鍵變小,變成「auth-token」。這是令人困惑的。 – lucassp

+0

@lucassp可能是這個 - http://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive – KrIsHnA

65

你可以使用默認的標頭的角度1.0.x的

$http.defaults.headers.common['Authentication'] = 'authentication'; 

或角1.1.x版本+請求攔截器:

myapp.factory('httpRequestInterceptor', function() { 
    return { 
    request: function (config) { 

     // use this to destroying other existing headers 
     config.headers = {'Authentication':'authentication'} 

     // use this to prevent destroying other existing headers 
     // config.headers['Authorization'] = 'authentication'; 

     return config; 
    } 
    }; 
}); 

myapp.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('httpRequestInterceptor'); 
}); 

由於工廠/服務是單身,這隻要您在實例化服務後不需要動態更改「身份驗證」值即可。

+0

我喜歡這個服務。謝謝! – grant

+2

有點困惑。我如何將其整合到我的應用程序中?我是否需要列出作爲依賴項,然後使用'$ httpProvider'而不是'$ http'? –

+0

將$ httpProvider注入掛起應用程序模塊的配置方法中。提供者是在服務被Angular注入到控制器之前配置服務的一種方式。 – Greg

1

添加到@Guria和@Panga

config.headers['X-Access-Token'] = $window.sessionStorage.token; 

一個以上響應可以用x存取令牌標頭,如JWT(jsonwebtoken)。 當用戶首次進行身份驗證時,我將JWT存儲在會話存儲中。

相關問題