我正在使用 angular 来 POST 到身份验证端点;在服务器端,我可以看到请求成功,并且设置了正确的 CORS header 。 Angular 的来源是 http://localhost:9000
在服务器端,预检 OPTIONS
请求总是返回一个 200
,所以这看起来没问题。
在客户端,$http.post
总是失败,错误代码为 0,从其他研究来看,这表明 CORS 仍然存在问题。我已经阅读了规范并尝试了许多其他答案,但仍然缺少一些东西。
这样的 Angular POST:
$http({
method: 'POST',
url: 'http://localhost:3000/auth/login',
data: {
username: $scope.username,
password: $scope.password
}
})
.then(function (response) {
/* etc. etc. */
}, function (response) {
/* This always triggers, with response.status = 0 */
console.log("ERROR: " + response.data);
console.log("Status: " + response.status);
console.log("Status text: " + response.statusText);
console.log("Headers: " + response.headers);
$scope.error = 'Something went wrong...';
});
使用 curl 调试服务器发回的内容,就是这样:
< HTTP/1.1 302 Found
< X-Powered-By: Express
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
< Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, Content-Length, X-Requested-With
< Access-Control-Allow-Credentials: true
< Set-Cookie: ua_session_token=(blahblah); Path=/
< Location: /
< Vary: Accept
< Content-Type: text/plain; charset=utf-8
< Content-Length: 23
< Date: Mon, 28 Dec 2015 15:08:17 GMT
< Connection: keep-alive
这就是我不知所措的原因,按照规范,服务器似乎在做正确的事情?
以下是服务器从客户端获取的请求 header :
HEADER host localhost:3000
HEADER content-type application/json;charset=UTF-8
HEADER origin http://localhost:9000
HEADER content-length 38
HEADER connection keep-alive
HEADER accept application/json, text/plain, */*
HEADER user-agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9
HEADER referer http://localhost:9000/
HEADER accept-language en-us
HEADER accept-encoding gzip, deflate
UPDATE 根据 this post 尝试了其他方法但没有成功.看起来 Access-Control-Allow-Headers
是区分大小写的,angular 正在发送请求 accept, origin, content-type
。我调整了服务器以同样的方式鹦鹉学舌,但没有运气。
最佳答案
好吧,我把头贴在键盘上几个小时后,我已经修好了。
答案似乎是 Angular 真的不喜欢获取重定向以响应 POST
。当我更改服务器端点以仅返回一个普通的身份验证 token 作为文本(无论如何它设置为 cookie 的相同 token )而不是返回重定向时, Angular POST
开始像魅力一样工作并下降一直到成功处理程序。
不确定我对此是否足够深入以了解为什么 Angular 会以这种方式表现;通过玩弄它,我发现如果服务器发送的重定向是到一个不存在的 (404) URL,那么这可以被复制,即使原始 POST 返回了有效的重定向。
关于angularjs - Angular $http.post 的 CORS 问题 - 成功的请求导致状态为 0 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496045/