[英]Angularjs set a authorization header
我試圖在我的請求中放置一個授權標頭,但它不起作用。
我正在使用這個:
var config = {headers: {
'Authorization': token
}
};
return $http.get('http://localhost:3000/apis/users/all', config);
我也試過這個:
$http.defaults.headers.common['Authorization'] = token;
但是在這兩種情況下,我都在后端請求中得到了這個標頭:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:es-ES,es;q=0.8,ca;q=0.6,en;q=0.4,gl;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
我需要這樣的東西:
Authorization: token
但我得到了這個:
Access-Control-Request-Headers:accept, authorization
然后,我在任何地方都沒有令牌值。
我在后端使用 expressjs,我在 CORS 中使用它:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
next();
});
還說使用 chrome 擴展 Advance Rest Client 進行測試它工作正常。 在請求頭中有一個 Authorization: valueOfToken..
非常感謝。
授權不能簡單明了。
指定天氣其Basic
或Bearer
授權
就像是
$http.defaults.headers.common['Authorization'] = 'Basic ' + token;
或者
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
我遇到了同樣的問題,結果證明該問題與服務器端的 Apache 配置有關。 我確實發現在這里可能對您有用的一件事是,我的授權令牌是在預檢請求標頭中發送的,而不是在主請求中發送的,因此當您查看它時,它可能不會出現在請求的標頭中開發者工具。
我正在設置我的默認值:
app.config(function($httpProvider) {
$httpProvider.defaults.common['Authorization'] = token;
// For angular 1.5, use:
// $httpProvider.defaults.headers.common['Authorization'] = token;
});
嘗試這個:
$http({
url : "127.0.0.1/login",
method : 'GET',
headers : {
Content-Type : 'application/json',
Authorization: token
}
}).success(function(data){
alert("login Successfully");
}).error(function(error){
alert("login error");
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.