2

I am developing a simple SPA application and trying to access a Dynamics 365 for Operations JSON-Based custom service. I am using ADAL.js library for authentication. The way for authentication I am following from This Dynamics Community thread.

But opportunity, after successfully getting the valid token, and calling my target api with acquired token, I am unable to call the API and getting CORS error.

PSB screenshot for the same

enter image description here

Below is my code sample:

    var req = new XMLHttpRequest()
   req.open("POST", organizationURI + "/api/services/ServiceGroup/Service/Operaton", true);

   //Set Bearer token
    req.setRequestHeader("Authorization", "Bearer " + token);
   req.setRequestHeader("Accept", "application/json");
   req.setRequestHeader("Content-Type", "application/json");

   req.onreadystatechange = function () {
    if (this.readyState == 4 /* complete */) {
     req.onreadystatechange = null;
     if (this.status == 200) {
      var empData = JSON.parse(this.response).value;
      console.log(empData);
     }
     else {
      var error = JSON.parse(this.response).error;
      console.log(error.message);
      errorMessage.textContent = error.message;
     }
    }
   };
   req.send();
Jan B. Kjeldsen
  • 17,817
  • 5
  • 32
  • 50

1 Answers1

1

You are getting this error, because your localhost conflicts with service domain. CORS - Cross Origin Resource Sharing issue.

Probably you have to add this snippet:

req.setRequestHeader('Access-Control-Allow-Origin', '*');

Still if conflict comes between your hosted SPA & Dynamics API, have to solve it.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors