Search code examples
jqueryajaxrestoffice365-appsoffice365api

JQuery Ajax requests to Microsoft Office365 Unified API Failing with Error Code 0


I'm currently trying to authenticate with the Microsoft Unified API to retrieve data. I've followed their deep dive which goes through the connection in Fiddler, and managed success with it. I'm now trying to convert this into code to run on a test website.

I have to create a POST request to the specified URL, which I have done via the following code:

var url = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
var data = 'grant_type=authorization_code' +
        '&redirect_uri=http://localhost:61104/Views/Home.html' +
        '&client_id=' + clientId +
        '&client_secret=' + clientSecret + 
        '&resource=https://graph.microsoft.com' +
        '&code=' + oauthCode;

$.ajax({
        type: "POST",
        url: url,
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: data,
        success: function (a, b) {
            alert('success');
        },
        error: function (a, b, c) {
            alert('fail');
        }
    });

However, this hits the error function, and the response gives me nothing except "error code 0". I've tried removing all data and headers and just posting to the URL, and again I get error code 0.

I've googled around and ensured that it's not my page refreshing or reloading, which it isn't. I tested this by posting to another REST service, which worked fine.

This is the first I've done with oAuth and posting so I assume i'm making a rookie mistake somewhere. What am I missing? Thanks.

Edit: To add, I tried a bare minimum request, with just:

$.ajax({
        type: "POST",
        url: url
}

and it still fails with error 0. I replicated this in Fiddler, and I got back the expected response (Error 400).


Solution

  • I solved this by adding:

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

    to the web.config file. I also had to enable cross site scripting in IE settings.