AngularJS $http 从失败的 CORS 请求返回状态码 0

AngularJS $http returns status code 0 from failed CORS request(AngularJS $http 从失败的 CORS 请求返回状态码 0)

本文介绍了AngularJS $http 从失败的 CORS 请求返回状态码 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经找遍了这个.基本上我们使用的是跨域请求的 $http 请求.我们的服务器允许域,当请求返回 200 时,一切正常.但是,无论何时我们的服务器返回一个错误,500、401 等等,Angular 都会认为这是一个 CORS 问题.

Okay, I've looked all over for this. Basically we're using $http request that ARE cross domain requests. Our server allows the domain and when a request returns 200, everything is OK. However, anytime our server returns an error, 500, 401, whatever, Angular thinks it's a CORS issue.

我使用 Fiddler 调试了响应以验证我的服务器正在返回 500,但 Angular 会阻塞它.

I debugged the response with Fiddler to verify my server IS returning a 500, yet Angular chokes on it.

这是请求:

       var params = {
            url: "fakehost/example",
            method: 'GET',
            headers: {
                "Authorization": "Basic encodedAuthExample"
            }
        };

       $http(params).then(
            function (response) { // success 

            },
            function (error) { // error 
                 // error.status is always 0, never includes data error msg
            });

然后在控制台中,我会看到这个:

Then in the console, I will see this:

XMLHttpRequest 无法加载 fakehost/example.请求的资源上不存在Access-Control-Allow-Origin"标头.因此,Origin 'mylocalhost:5750' 不允许访问.

XMLHttpRequest cannot load fakehost/example. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mylocalhost:5750' is therefore not allowed access.

然而,在提琴手中,真正的反应是:

Yet, in fiddler, the true response is:

HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 26 Aug 2014 12:18:17 GMT
Content-Length: 5683

{"errorId":null,"errorMessage":"Index was outside the bounds of the array.","errorDescription":"Stack trace here"}

我正在使用 AngularJS v1.2.16

I'm on AngularJS v1.2.16

推荐答案

我想我找到了答案,看起来你必须在你的 asp.net 管道中注入正确的 CORS 标头,如上所述 这里.

I think I found an answer, looks like you will have to inject in your asp.net pipeline the correct CORS headers, as mentioned here.

这篇关于AngularJS $http 从失败的 CORS 请求返回状态码 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:AngularJS $http 从失败的 CORS 请求返回状态码 0

基础教程推荐