【发布时间】:2016-11-02 11:42:45
【问题描述】:
我正在使用https://spring.io/guides/tutorials/spring-security-and-angular-js 上的教程将 AngularJS 应用程序连接到 Spring Security 后端进行身份验证。
当我尝试登录时(用户名和密码已存在于后端),我在浏览器控制台中收到以下错误(我在 Chrome、Firefox 和 IE 中测试我的应用程序,它们都给了我同样的错误) .
错误是:
XMLHttpRequest cannot load http://SERVER_URL:4444/test/user.
Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
The response had HTTP status code 401.
代码:
var auth = angular.module("Admin");
authService.service("AuthService", function($http, $rootScope){
this.login = function(credentials){
var headers = credentials ? {authorization: "Basic " + btoa(credentials.username + ":" + credentials.password)} : {};
$http.get("http://SERVER_URL:4444/test/user",{headers:headers})
.then(function(response){
console.log("success");
$rootScope.authenticated = true;
}, function(){
console.log("failed");
$rootScope.authenticated = false;
});
};
});
当我在浏览器中访问相同的链接时,我得到了验证框,我输入了用户名和密码,我可以看到结果。但是我不明白为什么我不能通过 $http() 成功访问同一个链接。
正确的做法是什么?我已经阅读了许多帖子和问答,但没有一个能解决问题。我只是不明白发生了什么。
【问题讨论】:
-
"当我在浏览器中访问同一个链接时......我可以看到结果。但我不明白为什么我不能通过 $http() 访问同一个链接成功” 所以你使用
CORS这个词知道它的意思。顺便说一句,您链接到的教程解释了如何添加对 CORS 的支持,所以我想知道您为什么“花了几天时间在谷歌上搜索”。
标签: javascript java angularjs spring spring-mvc