Express JS 应用无法识别 Angular 发送的授权令牌

Express JS app does not recognize authorization token send by Angular

我正在开发 api,它作为 Express JS 应用程序运行,我正在使用 Angular JS 向 api.

发送请求

api 需要在 header 中发送授权,而我在 angular 中努力做到这一点。

我的 Express JS 代码:

app.all('*', function(req, res, next) {
// add details of what is allowed in HTTP request headers to the response headers
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Max-Age', '86400');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
// the next() function continues execution and will move onto the requested URL/URI
next();
});

app.use(function(req, res, next) {

var header=req.headers['authorization']||'',        // get the header
    token=header.split(/\s+/).pop()||'',            // and the encoded auth token
    auth=new Buffer(token, 'base64').toString(),    // convert from base64
    parts=auth.split(/:/),                          // split on colon
    username=parts[0],
    password=parts[1];

r(header);
r(token);
r(auth);
r(username);
r(password);

if(username=='usr' && password=='pwd'){
    next();
}else{

    res.set('WWW-Authenticate', 'Basic realm="Birds.cz login"');
    res.status(401).send({error:'auth'});
  }
}

当我使用 curl 发送这个:curl --user usr:pwd http://127.0.0.1:8000/v1/login 时,控制台打印:

Basic dXNyOnB3ZA==
dXNyOnB3ZA==
usr:pwd
usr
pwd

这是正确的。

我的 angular 服务如下所示:

function testLogin() {
  $http({
     method  :'GET',
     url:'http://127.0.0.1:8000/v1/login',
        }).success(function(data, status, headers, config) {
            alert(data);
        }).error(function(data, status, headers, config) {
            alert('error');
        }).catch(function(error){
            alert('catch' + JSON.stringify(error));
        });

}

在整个 angular 应用程序的配置中,我有:

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

//Enable cross domain calls
$httpProvider.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

// insert authorization header
var string = 'usr:pwd';
var encodedString = btoa(string);
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + encodedString;

...
}

当我从 Angular 发出请求时,节点 js 控制台打印五个空行,因此根本无法识别授权 header。

有什么想法吗?

EDIT 当我在 http 请求 header 中使用 Authorization 时,服务器 returns 错误 0,但是当我省略它时,它returns 错误 401,这是应该的。在我看来,提供 Authorization header 会在发送 401 错误代码之前破坏服务器端的代码。

编辑 2 当我在节点 js 应用程序中记录请求 header 时,它根本不显示令牌 Authorization

{ host: '127.0.0.1:8000',
'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'cs,en-US;q=0.7,en;q=0.3',
'accept-encoding': 'gzip, deflate',
origin: 'http://localhost',
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization',
connection: 'keep-alive' }

编辑 3 这是请求的 header,在 firebug

中捕获
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language cs,en-US;q=0.7,en;q=0.3
Access-Control-Request-He...    authorization
Access-Control-Request-Me...    GET
Connection  keep-alive
Host    127.0.0.1:8000
Origin  http://localhost
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0

允许来自不同域的请求,在服务器端添加此代码以解决 CORS 相关错误 -

var resolveCrossDomain = function(req, res,next) {

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
    res.header("Access-Control-Allow-Credentials", true);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }
}; 
    app.use(resolveCrossDomain);