Request succeeds on server but results in CORS error in browser

Viewed 11611

I do an HTTP POST request to the microsoft login to get an access token to use with the mail API, the request succeeds but the code goes to the error clause of my code.

requestAccessToken(code: string)
{
console.log("request access token");
if (code) {
  var headers = new Headers();
  headers.append("Content-Type", 'application/x-www-form-urlencoded');
  headers.append('Accept', 'application/json');
  var requestoptions = new RequestOptions({
    headers: headers
  });
  var body = `grant_type=authorization_code&
              redirect_uri=http://localhost:4200&
              code=`+ code + `&
              client_id=4e[................]5ab&
              client_secret=CE[..............]BC`;

  this.http.post("https://login.microsoftonline.com/common/oauth2/v2.0/token", body, requestoptions).map((res: Response) =>
  {
    console.log("response given");
    const data = res.json();
  }).subscribe( (data) => {
     console.log("The data is = " + data); 
  }, error => { 
    console.log("The error is = " + error)
  });
}

The browser console shows this: XMLHttpRequest cannot load https://login.microsoftonline.com/common/oauth2/v2.0/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. zone.js:2019 XHR failed loading: POST "https://login.microsoftonline.com/common/oauth2/v2.0/token". outlook.service.ts:96 The error is = Response with status: 0 for URL: null

here's a screenshot to show it better Console error log

Now the real problem is that my request succeeds as shown below: Browsers' network tab

and the response shows my access token. So why cannot I get it from code? Why does it go the error-clause.

2 Answers
Related