Prevent XHR from responding to OPTIONS method

Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handling of OPTIONS requests to address any potential CORS issues.

While my API effectively handles these OPTIONS requests, a challenge arises when the server responds to the OPTIONS request within client-side JavaScript. It seems to interpret this response as the actual response, thus disregarding the legitimate one. How can I prevent XHR from accepting the OPTIONS response?

Below is the code snippet for my function:

function makeRequest(method, url, data) {
  document.body.style.cursor = "wait";
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
      if (this.status == 200) {
        authToken = this.getResponseHeader('Authorization');
        document.body.style.cursor = "initial";
        console.log('responseText');
        console.log(this.responseText);
        resolve(JSON.parse(this.responseText));
      } else if (this.status == 403) {
        logout();
        document.body.style.cursor = "initial";
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      } else {
        document.body.innerHTML = 'Error: ' + this.responseText;
        document.body.style.cursor = "initial";
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      document.body.innerHTML = 'Error: ' + this.responseText;
      document.body.style.cursor = "initial";
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", authToken);
    xhr.send(data);
  });
}

Although this approach functions correctly, it poses limitations as my application requires the ability to await responses from the function before proceeding with subsequent actions:

function retrieveCategories(active) {
  document.body.style.cursor = "wait";
  var data = JSON.stringify({ "active": active });
  console.log(data);

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;

  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4 && this.status == 403) {
      logout();
      document.body.style.cursor = "initial";
    } else if (this.readyState === 4 && this.status != 200) {
      document.body.innerHTML = 'Error: ' + this.responseText;
      document.body.style.cursor = "initial";
    } else if (this.readyState === 4 && this.status == 200) {
      authToken = this.getResponseHeader('Authorization');
      categories = JSON.parse(this.responseText);
      document.body.style.cursor = "initial";
    }
  });

  xhr.open("POST", "http://127.0.0.1:7071/retrievecategories");
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", authToken);

  xhr.send(data);
}

Any suggestions or insights on how to overcome this issue would be greatly welcomed!

Answer №1

It turns out that @Quentin was spot on - the XHR was failing to handle the OPTIONS response due to a flawed server response.

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

Is it possible to verify age on a date field in vanilla JavaScript?

How can I validate the age on a date input field? If someone is 18 or older, they will be valid. Otherwise, an error message should be displayed. Can you help me with this? ...

Which is the superior choice: Classic Ajax or jQuery Ajax?

I have a question about using AJAX. I'm stuck between choosing traditional AJAX and jQuery AJAX. When I use jQuery AJAX, sometimes it behaves strangely in Internet Explorer. This is surprising to me because jQuery is supposed to be a cross-browser lib ...

Ways to distinguish jquery response apart from using $.post method?

Using jquery $.post method: $.post( 'includes/studiesAjax/addTryb.php', {inputVL: inputVL}, function(res){ $("#container").html(res); } ); The response contains a long html code. I am interested in extracting data from ...

In ES6, instantiate a fresh new instance of this

Can a new instance of self/this be generated using ES6 inside a static method? For instance; class myClass { static model() { return new this; } } Is there a standard approach for this situation? Thank you very much. ...

How can I implement the dynamic loading of components using the Vue 3 composition API?

My goal is to dynamically load a component with the name retrieved from the database, however, I keep encountering the error [Vue warn]: Component is missing template or render function. import SimpleQuestions from '@/components/SimpleQuestions.vue&ap ...

Having trouble with Grunt and Autoprefixer integration not functioning properly

Joining a non-profit open source project, I wanted to contribute by helping out, but I'm struggling with Grunt configuration. Despite my research, I can't seem to figure out why it's not working. I am trying to integrate a plugin that allow ...

Manipulating arrays of objects with handlebars.js

I need help with my node.js app that is returning JSON data for computers. { computers: { john: { cpu: "intel", ram: "8MB", hd: "1TB" }, jane: { cpu: "intel", ram: "12MB", hd: "500GB" }, mary: { ...

Rotating through elements in timed intervals

After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

Tips for verifying the inclusion of the + symbol in the country code in Angular 7

My form includes a text box where users can input a country code preceded by a + sign. If a user enters only numbers, we need to restrict that action and prompt them to enter the country code with a + sign, for example: +91, +230, ... I've been tryin ...

What is the best way to manage a JSON feed that does not provide any results?

Excuse my lack of experience as I pose my first question. Using FullCalendar 5.10.1, I am working on retrieving events dynamically associated with Festivals. I have followed the 'events (as a json feed)' pattern from the documentation. When ther ...

stop automatic resizing of windows

My CSS is written using percentages. I need to maintain the percentages intact. Is there a way to stop the layout from changing when the browser window is resized? I want the percentages to remain unaffected, even when the browser window is being resized ...

Unfortunate escapement of characters discovered in variable that returns JSON image source

I am currently utilizing Google Tag Manager to incorporate the 'article' JSON markup and retrieve different variables for modifying specific sections on particular pages. Among the elements I am attempting to obtain is the image source. At prese ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...

jQuery is unable to locate elements

Here is a JavaScript code snippet that I have: (function($, undefined) { $("a").click(function(event) { //or another elemtnt alert('Hello!'); }) })(jQuery); Also, here is the link being referenced in the code: <a href="http: ...

Obtaining NodeJS from a mysterious subdirectory

-- plugins ---- myplugin1 ------ core ---- myplugin2 ------ core If this represents the directory structure, is there a method to import all core directories from plugins without specifying the specific plugin names like myplugin1? require('/plugins ...

Best practice for validating a form using React: Why the state doesn't update immediately with useState and onSubmit

I'm currently working on implementing a custom form validation for my React project using Typescript. However, I've encountered an issue with the useState hook not updating the state containing errors immediately upon form submission. Let me illu ...

Assigning specific class names to elements within an array using JavaScript

Currently, I'm attempting to assign a unique className to option elements within a select element by utilizing a conditional if statement. The goal is to apply one class name to the first half of the array and a different class name to the second half ...

Triggering a jQuery ajax request upon pressing a key on the keyboard

When a user inputs text into an <input> element, I'm using ajax to send a request to the server. Here's how it looks: $('#my-input').bind("input", function(event){ // ajax request code }); My concern is that too many requests ...