Mike Marks
Mike Marks

Reputation: 10139

Making a call to a WebAPI GET method from client side JavaScript AJAX, getting error

I have a WebAPI hosted on my local machine and I am trying to call it from an app via JavaScript/JQuery/Ajax. The idea is that this WebAPI will live on a different server than the server making the call TO the WebAPI (cross domain). However, this isn't the case right now - I am working on localhost.

When I go to the URL http://localhost/AppTools.WebAPI/api/BulletinBoard/AppName, I get a collection of JSON returned, as expected.

But, and I think I might be doing this part wrong, when I try to get the data via an AJAX call (see code below), the error part of the AJAX call gets hit, and I have a message box returning the error details:

enter image description here

Here's my client side code:

$(document).ready(function () {
            $.ajax({
                url: 'http://localhost/AppTools.WebAPI/api/BulletinBoard/AppName',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    WriteResponse(data);
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
});

function WriteResponse(messages) {
            var strResult = "<table><th>AppId</th><th>Message</th>";
            $.each(messages, function (index, message) {
                strResult += "<tr><td>" + message.AppId + "</td><td> " + message.Message + "</td></tr>";
            });
            strResult += "</table>";
            $("#divResult").html(strResult);
        }

What am I doing wrong?

Upvotes: 1

Views: 1854

Answers (1)

Lin
Lin

Reputation: 15188

I think it's still cross domain problem. Add below code to your Web.config file, it should work.

<system.webServer>
 <httpProtocol>
  <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
 </httpProtocol>
</system.webServer>

Upvotes: 1

Related Questions