Server request successful, but CORS error occurs in browser

When I make an HTTP POST request to the Microsoft login in order to obtain an access token for use with the mail API, the request is successful but my code still goes to the error clause.

requestAccessToken(code: string)
{
console.log("Requesting 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 received");
    const data = res.json();
  }).subscribe( (data) => {
     console.log("The data is = " + data); 
  }, error => { 
    console.log("The error is = " + error)
  });
}

The browser console displays the following error message: XMLHttpRequest cannot load . 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 "". outlook.service.ts:96 The error is = Response with status: 0 for URL: null

Here's a screenshot for better visualization: https://i.sstatic.net/cHO0W.png

However, it seems that despite the error messages, my request is actually successful as indicated here: https://i.sstatic.net/YVgeR.png

So why does my code still go to the error clause instead of retrieving the access token?

Answer №1

When sending a cross-origin request to a server without receiving the Access-Control-Allow-Origin response header, the behavior you are observing is quite expected.

The process involves browser restrictions being enforced at the point of origin. Servers do not typically block cross-origin requests; they simply accept and process them. However, if the server's response lacks the necessary Access-Control-Allow-Origin header, the browser will prevent your frontend code from accessing it.

In instances where your request triggers a preflight, the browser may allow the request to be sent but restrict access to the response in JavaScript code. This can lead to challenges in retrieving and utilizing the information received from the server, especially in cases like GET requests where the response is crucial for further actions.

While POST requests may still technically succeed in altering server state even without full access to the response, the inability to retrieve responses from certain requests can pose significant limitations on the functionality and effectiveness of your frontend code.

Answer №2

Your post has been properly tagged with "cors", indicating that modern browsers restrict access to endpoints across different domains unless the endpoint sends cors-headers allowing access.

If you check your network tab, you will see an OPTIONS request to . This is known as a preflight-request, which verifies the presence of Access-Control-Allow-Origin and Access-Control-Allow-Methods headers. The former should include your domain or *, while the latter should include POST or *.

Although I am not well-versed in office APIs, there should be a method to configure your app as a valid endpoint. You may find this post helpful: https://msdn.microsoft.com/en-us/office/office365/howto/create-web-apps-using-cors-to-access-files-in-office-365

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

Tips for sorting through a multi-dimensional array of objects

I'm looking to filter this array based on the attributevalue. For example, if I search for blue color, I want all shirts in blue color to be displayed. And then if I further search for cotton fabric in blue color, I want all cotton products with blue ...

A guide on accessing and merging values in an array of objects using index positions in node.js

I have retrieved a collection from MongoDB and stored it in an array using a foreach loop. Now, I need to iterate through this array and format the output as shown below. Each member object should be correctly associated with the "lead" field based on thei ...

Transferring information to a navigated module using Angular2

I am currently facing a scenario where I have a component being loaded via routing, and my goal is to pass data from the parent component into this child component. How exactly can I achieve this task effectively? Parent Component Class export class Home ...

Downgrading from Angular 2.4.9 to 2.4.8: A Step-by-Step Guide

I've searched everywhere and can't figure out how to downgrade @angular/core to version 2.4.8. I installed @angular/cli with version 1.0.0-rc.0 because 1.0.0-rc.1 has some bugs. Now I want to downgrade @angular/core as well because I can't ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

What is the reason behind the absence of unwrapping when utilizing a ref as an element within a reactive array or reactive Map?

The Vue documentation states the following: Unlike reactive objects, there is no unwrapping performed when the ref is accessed as an element of a reactive array or a native collection type like Map Here are some examples provided in the documentation: c ...

sending a file using ajax and handling it with php

Curious if there's a way to upload a binary file through ajax and php, without having to refresh the entire page like with a traditional html form. I've been able to gather input from radio buttons and text boxes using forms and javascript, but w ...

Mongoose fails to store a newly created document

I am trying to store a MongoDB document in my Node server using Mongoose: mongoose.connect('mongodb://localhost/appJobs'); var db = mongoose.connection; db.on('error', function() {console.log("error")}); db.once('open', funct ...

Tips on displaying or hiding the close button on the task pane of an online Excel document with an Office.js add-in

Working with office.js and Angular 6 to develop my add-in, I have implemented event listeners that run in the background. However, these events require the right side task pane to remain open or minimized. I am seeking a solution to prevent users from clos ...

Exploring the process of defining methods within a child Vue component

componentA.vue: <script lang="ts"> import { Vue } from 'vue-property-decorator' @Component export default class ComponentA extends Vue { public methodA(): void { // } } </script> componentB.vue: <template> ...

Using nextJS to establish a context within a Server Component and incorporating a new library

I attempted to incorporate Framer Motion into my project, but when I added it, an error occurred. The error message displayed was: TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Fo ...

Sorting technique failing to reorganize list

I'm currently troubleshooting why my sorting function is not functioning as expected. My goal is for it to operate similarly to this example: https://codepen.io/levit/pen/abmXgBR The data I am working with is retrieved from an API: <BookCard v-fo ...

What is the formula for determining the REAL innerWidth and innerHeight?

I am currently working on a responsive website using Bootstrap and I am looking to create an element that perfectly fits the screen size. When I set the height/width to 100%, the browser includes the toolbar, other tabs, and the Windows taskbar in the cal ...

AngularJS: Issues with retrieving response headers following a $resource $save operation

When I run the $save function, which triggers my angularJS $resource to send a POST request to my API, everything seems to be working fine. I can successfully debug into the success callback handler and confirm that the object is created in my API. myObj. ...

Utilizing the props value for emission within the emits array: A guide

While attempting to list a custom event in the component's emits option, I encountered a console error. The code looked like this: PARENT <Btn event-name="toggleSideMenu" @toggle-side-menu="toggleHandler"> togg ...

Vue Component Rendering Before Vuex Data is Ready

I am facing a challenge with my Vue2 component that depends on Vuex to fetch the currently selected node (infoNode) and display its data to the user. In my beforeCreate function, Axios is used to retrieve the top level nodes and set the 'infoNode&apos ...

Tips for activating numerous effects in an Angular app when the translation culture shifts

I am currently developing an Angular 13 application that incorporates internationalization. In my project, when the user changes the culture, all static resources are automatically translated, but I faced a challenge when trying to reload specific data tha ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

What methods are available for me to apply a filter on an API?

I am working with the MovieDB API and want to implement a search bar for filtering. I could really use some assistance as I'm not sure how to get started. The requirement is to utilize JavaScript/jQuery for the code and only filter based on keywords. ...