Reputation: 1029
I have an Azure ASP.Net web role running my web UI. I have an MvC4 REST API running in a separate web role in the same Azure instance. Azure puts the web UI on port 80 and the API on port 8080. So when I want to send an AJAX request from a web page to the REST API, I need to munge the URL to change the port to connect to the REST API instead of the web UI web role.
I have this JavaScript in my page:
function getWebAPIURL(criteria) {
// The generated code had this:
// var uri = 'api/values';
// But that only works if the API is running in the same Azure web role as the UI,
// which it isn't - it's running in the same domain but on port 8080. So we have
// to munge the URL a bit to get the correct URL for the RESTful API
var strWebAPIURL = window.location.protocol + '://' +
window.location.hostname + ':8080' +
'/api/values';
// If provided,critiera is appended in REST style, e.g api/values/5
if (criteria != undefined && criteria != null && criteria != '') {
strWebAPIURL = strWebAPIURL + '/' + criteria;
}
// console.log(strWebAPIURL);
return strWebAPIURL;
}
$(document).ready(function () {
// Send an AJAX request
$.getJSON(getWebAPIURL())
.done(function (data) {
// On success, 'data' contains a list of files.
$('#File').text(formatReturnedItems(data));
});
});
When I stop in the debugger, I see that the URL returned from getWebAPIURL is (correctly, I believe)
http://xxxx.cloudapp.net:8080/api/values
But I get back a 404 error from the getJSON call. When I look at Fiddler, I see that the URL is apparently going to
i.e. it's continuing to use the main domain as the base and taking my xxxx.cloudapp.net:8080 as a sub-part of the URL. I believe this has something to do with the prevention against cross-domain calls.
But this seems like a very common case - I have a web UI and an API layer that is REST. It doesn't seem like I'm trying to do something really bizarre here that should be hard - so I have the feeling I'm just doing something simple wrong.
Hoe do others do this?
Upvotes: 1
Views: 307
Reputation: 11486
window.location.protocol
will return the protocol with a trailing colon (ref). Therefore there isn't any need to include it in your JavaScript.
var strWebAPIURL = window.location.protocol + '//' +
window.location.hostname + ':8080' +
'/api/values';
The above code will create a valid URL so that the jQuery $.getJSON()
function doesn't feel the need to change it.
Upvotes: 1