user3369534
user3369534

Reputation: 125

ajax call from web api 2 failing

I'm trying to do a ajax call from jquery where I need data from my webservice (web api) to a phonegab app for my android.

I have installed Cors from Nuget and enabled this the service.

But when I test my service in Chrome I keep getting this error:

Refused to set unsafe header "Origin" jquery-1.10.2.js:8699 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

My Ajax code is:

function list() {
        var result = null;
    $.ajax(
        {
            url: 'mysite',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Origin", "*");
                xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            },
            contentType: 'application/json; charset=utf-8',
            type: 'GET',
            crossDomain: true,
            async: false,
            success: function (data) {
                result = data;
            }
        });
    return result;

};

Update

This is added to my webconfig

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

Upvotes: 0

Views: 226

Answers (1)

Quentin
Quentin

Reputation: 943560

The server you are requesting data from has to grant your JavaScript permission to access it.

Access-Control-Allow-Origin is a response header not a request header.

Here is a guide on how to enable Cross Origin Requests on your server.

Upvotes: 1

Related Questions