Ewald Bos
Ewald Bos

Reputation: 1770

Azure Mobile Service and Javascript

Hi there i am stuck and somehow don't find the solution. It seems simple but, well ok. Here it goes. I have a mobile service in Azure and i want to reach that one with javascript. How do i get around the 401 Unauthorized? I tried with the documentation supplied from MS but no luck. This is what i got so far (adding the key to the url is not working of course) what can i add to get it to work?

var client = new WindowsAzure.MobileServiceClient(
"https://cdshop.azure-mobile.net/",
"vGpqzyApJXXXXXXXXblQCWne73"
);

var getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
    var status = xhr.status;
    if (status == 200) {
        callback(null, xhr.response);
    } else {
        callback(status);
    }
};
xhr.send();
};


$(function () {
$('#clickme').click(function () {

    getJSON('http://cdshop.azure-mobile.net/api/cds/total?key=vGpqzyApJXXXXXXXXblQCWne73', function (err, data) {
if (err != null) {
    alert('Something went wrong: ' + err);
} else {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
}
    });
});
});

Upvotes: 0

Views: 56

Answers (1)

Eric Hedstrom
Eric Hedstrom

Reputation: 1627

If you are creating your own HTTP requests, you need to set a request header called X-ZUMO-APPLICATION with your Application Key, e.g. "vGpqzyApJXXXXXXXXblQCWne73", for tables and APIs that are set to "application" or "users". (Assuming you are still using Mobile Services; the newer App Service does not use this X-ZUMO-APPLICATION header.) Tables and APIs set for "users" also need an X-ZUMO-AUTH request header with the user's authentication token.

Alternatively, you can use the MobileServiceClient you created in the first line, and it will do this for you. This page has examples for calling APIs and tables. For your example:

client.invokeApi("cds", {
    body: null,
    method: "get"
}).done(function (data) {
    alert('Your Json result is:  ' + data.result);
    result.innerText = data.result;
}, function(error) {
    alert('Something went wrong: ' + error);
});

Upvotes: 1

Related Questions