jQuery ajax call to cross domain returns status 40

2019-05-17 06:15发布

问题:

I've spent most of today trying to figure out why my jQuery ajax call in my stand-alone HTML page to a cross domain ASP.Net MVC Web API call is returning the proper JSON data, but I'm getting the following error message in my error portion of ajax call:

Object { readyState=4, status=404, statusText="error", more...}

I'm using jQuery 2.0.3. Here's my ajax call code:

    $.ajax
({
    type: "GET",
    beforeSend: function (xhr, settings)
    {
        xhr.setRequestHeader("Authorization", "95d11869-a2ad-4925-8a16-ee23c82909ac");
    },
    url: url,
    dataType: "json",
    processData: false,
    crossDomain: true,
    success: function (jsonFromServer)
    {
        alert(JSON.stringify(jsonFromServer));
    },
    error: function (xhr, textStatus, errorThrown)
    {
        if (typeof console === 'object' && typeof console.log === 'function')
        {
            console.log(xhr);
            console.log(textStatus);
            console.log(errorThrown);
        }
    }       
});

I can validate the call to my WEB API service is working 2 different ways: via Fiddler and via network traffic tab in firebug. Both ways show 2 different calls to my server: preflight and actual request. Fiddler shows the actual JSON data results and I've validated them against JSLint and the JSON is formatted correctly. The network traffic tab's second entry to my service indicates a 200 status but the response is empty.

Here's my request header:

GET /api/gamelist HTTP/1.1
Host: local.XXXXXX.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: 95d11869-a2ad-4925-8a16-ee23c82909ac
Referer: http://127.0.0.1:52148/index.html
Origin: http://127.0.0.1:52148
Connection: keep-alive

Here's my response header:

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://127.0.0.1:52148
X-AspNet-Version: 4.0.30319
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Access-Control-Max-Age: 86400
Date: Fri, 04 Oct 2013 20:22:43 GMT
Content-Length: 683

I've read through a lot of posts and see examples that people say works. I'm not sure what I'm doing wrong. Does anyone have any insight please?

UPDATE

I turned on Firefox's WebDeveloper Network tool to monitor transmissions of requests. I noticed it's reporting the following for the cros domain call to my server:

Syntax Error: JSON.parse:unexpected end of data.

Here's the JSON data returned from my service call I obtained via fiddler:

{"Player":{"PersonId":33,"PersonName":"Anonymous User","UserKey":"95D11869-A2AD-4925-8A16-EE23C82909AC","EmailAddress":"unknown"},"GameList":[{"GameId":17,"QuestionTypeId":1,"QuestionTypeName":"Baseball","QuestionId":6,"QuestionName":"Basbeball Team Names","GameTypeId":2,"GameTypeName":"Solo","TotalAvailablePoints":141,"StartDate":"2013-10-04T11:17:10.277","WhosTurnIsItId":33,"WhosTurnName":"Anonymous User"},{"GameId":18,"QuestionTypeId":1,"QuestionTypeName":"Baseball","QuestionId":3,"QuestionName":"World Series Winners","GameTypeId":2,"GameTypeName":"Solo","TotalAvailablePoints":149,"StartDate":"2013-10-04T11:17:10.277","WhosTurnIsItId":33,"WhosTurnName":"Anonymous User"}]}

I've pasted this JSON in JSLint and it says it's formatted correctly. I'm not sure what's going on. Any insight?

回答1:

I had this very issue as well and solved it as follows:

  • Change the dataType from 'json' to 'jsonp' in the AJAX call
  • Add this NuGet package to the Web API project: WebApiContrib.Formatting.Jsonp
  • Register the JsonpFormatter by calling this from Global.asax:

    configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(configuration.Formatters.JsonFormatter));
    

The issue is that the Web API doesn't know how to speak jsonp, which is the only dataType that can be used in cross-domain AJAX calls.