【发布时间】:2015-09-05 15:32:14
【问题描述】:
我一直在寻找一些类似的问题以寻找答案,但找不到。我有一个带有 express 的 node.js 服务器:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Headers");
next();
});
app.use(express.static(__dirname+'/assets'));
app.use(bodyParser.json());
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/index.html');
});
AngularJS 处理 GET 请求到 REST API。它们由搜索表单中的 keyup 事件触发。 app.config:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'Authorization, Access-Control-Allow-Headers';
$httpProvider.interceptors.push('TokenInterceptor');
});
...以及请求代码本身:
$scope.requestMovies = function() {
$http.get('http://www.omdbapi.com/?s=' + $scope.titleToSearch +
'&type=movie&r=json')
.success(function(data, status, headers, config) {
$scope.movies = data.Search;
})
.error(function(data, status, headers, config) {
alert("No movie found");
});
};
在我向我的项目添加身份验证(因此是拦截器)之前,这一直很好,从那时起我总是收到一条错误消息XMLHttpRequest cannot load http://www.omdbapi.com/?s=darkmovie&type=movie&r=json. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers.
即使我确实授权了前端和后端的标头。 Firefox 中的情况与 Chrome 中的情况相同。我做错了什么?
更新
忘记发布我的 TokenInterceptor 服务:
app.service('TokenInterceptor', function($q, $window, $location, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
requestError: function(rejection) {
return $q.reject(rejection);
},
/* Set Authentication.isAuthenticated to true if 200 received */
response: function (response) {
if (response !== null && response.status == 200 && $window.sessionStorage.token && !AuthenticationService.isAuthenticated) {
AuthenticationService.isAuthenticated = true;
}
return response || $q.when(response);
},
/* Revoke client authentication if 401 is received */
responseError: function(rejection) {
if (rejection !== null && rejection.status === 401 && ($window.sessionStorage.token || AuthenticationService.isAuthenticated)) {
delete $window.sessionStorage.token;
AuthenticationService.isAuthenticated = false;
$location.path("/");
}
return $q.reject(rejection);
}
};
});
虽然我仍然看不出有什么问题。这应该是一种在每次角度视图发生变化时检查服务器发送的授权令牌的方法。
【问题讨论】:
标签: javascript angularjs node.js http http-headers