Absence of receiving any HTTP error codes when making REST calls

In our application, it is crucial to differentiate between 400 and 500 range error codes for distinct processes.

Let's consider three REST calls:

  • The first returns a status code of 200,
  • the second returns 401,
  • and the third returns 502

Initially, while using aurelia-http-client, I encountered an unexpected http error with code = 0 in the promise reject callback.

Update: Switching to aurelia-fetch-client resulted in receiving only a string as an error response, eliminating it as a viable option.

I then experimented with an ajax call and a basic XMLHttpRequest, but faced the same issue. The statusCode was always 0 for errors above the 200 range.

Update: To provide context, I am using Version 63.0.3239.132 of Chrome.

Attempts So Far:

  • I made about five different variations for fetch requests.

    fetch(url, {
      method: requestMessage.method,
      headers,
      body: JSON.stringify(content)
    })
    .then((result) => {
      resolve(result)
    })
    .catch((error) => {
      reject(error); 
    });
    
  • This resulted in a string error being displayed.

Using aurelia-http-client:

    this.httpClient.createRequest(url)
      .asPut()
      .withContent(params)
      .send()
      .then((response) => {
        resolve(response);
      },
      (error) => {
        reject(error);
      });

- Errors consistently showed a StatusCode of 0

Additionally (Constructs a dynamic XmlHttpRequest):

private retryRequest(): void {
  var xhr = this.setupXhr();
  xhr.onreadystatechange = () => this.stateChange(xhr);
  setTimeout(() => {
    xhr.send(JSON.stringify(this.content));
  }, 1000);
}

private setupXhr(): XMLHttpRequest {
  var xhr = new XMLHttpRequest();
  xhr.open(this.method, this.url, true);
  xhr = this.addHeaders(xhr);
  return xhr;
}

private addHeaders(xhr: XMLHttpRequest): XMLHttpRequest {
  for (let key in this.headers) {
    if (this.headers.hasOwnProperty(key)) {
      xhr.setRequestHeader(this.headers[key].key, this.headers[key].value);
    }
  }
  return xhr;
}

private stateChange(xhr: XMLHttpRequest): void {
  logger.debug(' ::>> xhr = ', xhr);
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 400) {
      this.resolve(JSON.parse(xhr.response));
    } else if (xhr.status >= 500) {
      this.retryRequest();
    } else {
      // this.retryRequest();
      this.reject(xhr.response); // call after a # of fails for this ??? 
    }
  }
}
  • This function exclusively captures the 200 range HTTP status codes

Moreover:

    $.ajax({
      type: requestMessage.method,
      url,
      data: JSON.stringify(content),
      headers,
      success: (data) => {
        logger.debug(' ::>> rest call was a success ', data);
        resolve(data);
      },
      statusCode: {
        502: (jqXHR) => {
          logger.debug(' ::>> received 502 ');
          var retryAfter = jqXHR.getResponseHeader('Retry-After');
          retryAfter = parseInt(retryAfter, 10);
          if (!retryAfter) { retryAfter = 5 };
          setTimeout(query, retryAfter * 1000);
        }
      }
    });

- Despite specifying a 502 callback, it never triggers. I have attempted handling other status codes as well.

Could there be a solution to properly retrieve the error codes that I may have overlooked? Any assistance would be greatly appreciated.

Answer №1

I recently had a similar need and successfully tackled it with the following code snippet:

$.ajax({
        type: "POST",
        url: urlAjax,
        dataType: 'json',
        headers: headerValue,
        data: _dataValue,
        crossDomain: true,
        beforeSend: function () {
            // perform any necessary operations here
        },
        complete: function () {
            // carry out any post-request operations here
        },
        success: function (data) {
           // Handle all 2XX responses here
        },
        error: function (jqXHR, textStatus, error) {
            var Check = JSON.parse(jqXHR['responseText']);
            // This array contains detailed error information
        }
    }).done(function (rs, textStatus, xhr) {
        // Code to execute after the request is complete
    });

In the jqXHR, textstatus, and error parameters, you will find comprehensive details about any errors or status codes.

I hope this solution proves helpful for your needs.

Answer №2

Discovered the solution:

At first, I believed that implementing Harshal Bulsara's suggestion had resolved my problem. While it was a helpful idea, it did not address the root cause.

I eventually identified that our nginx server was not sending necessary headers in its response. After including the Access-Control-Allow-Origin header, I successfully received the correct statusCode.

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

Modified the object path and updated the Dirty stages for nested objects within Vue state

Imagine having an object that contains arrays of objects in some properties. Whenever changes are made to any field, whether it's within an object in an array or the main object itself, you want to mark that object as "dirty" using a code snippet like ...

Troubleshooting Issue with JQuery Date Picker: Date Not Valid

Encountering an issue when using the date from JQuery DatePicker in an SQL Statement variable, resulting in an error of invalid datetime string. Even after attempting to format it with DateTime.Parse or Convert.DateTime. JQuery DatePicker <script> ...

Error occurs in Angular 10 when reloading IFrame

My goal is to fetch the HTML string from an API and update an iframe with that string. The code works perfectly for the first load, but when the onBtnClick method is triggered a second time, it throws an error: VM3012:1 Uncaught SyntaxError: Identifier &ap ...

Determining the Testing Status of a Node Package Management (NPM) Package

As someone who is new to Node.js and NPM, I have a question that may seem naive. Is there a method to determine if a package published on NPM has been tested? And if so, can this process be automated? Are there any tools or frameworks available that can va ...

Following the upgrade of Angular, the webpack module source-map-loader is encountering an error: "this.getOptions is not a function"

Currently in the process of constructing my angular project using webpack alongside source-map-loader to extract source maps, like this: module.exports = { // ... module: { rules: [ { test: /\.js$/, enforce: "pre&quo ...

What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem. "A task for you: Calculate the average score of a class whose test scores have been graded by a teacher. Your mission is to complete the getAverage function, which receives an array of test sco ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being sto ...

Steps for Implementing an Event Listener in JavaScript

While working on a page in Chrome, I encountered an issue where I wanted a modal to show up when a user clicked on an image. However, the functionality was not working as expected on my localhost. Upon further inspection, I believe there might be a problem ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

`HTTP Streaming with Axios in a Node JS Environment`

I am currently facing an issue while attempting to stream price data via HTTP (I'm surprised they aren't using websockets..). I usually use axios for making REST API requests, however, I am struggling to handle 'Transfer Encoding': &apo ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

The functionality of form.serialize() seems to be malfunctioning

I encountered an issue with my webpage called "View Employee." When we click on it, all the employees are displayed with an edit button for each one. Below is the corresponding page: echo "<form class="form-horizontal id="update_form" name="update_form ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Is it possible to embed a Microsoft Teams meeting within an Iframe?

Is it possible for MS Teams to provide a URL of a video meeting that can be embedded in external locations, such as an iframe on my website? I attempted to add it like this: <iframe src="https://teams.microsoft.com/l/meetup-join/19%3ameeting_N2E3M ...

Pass a link by pressing Enter

Although the title may seem odd, I'll explain what I'm attempting to accomplish. I have a login form with two input fields, a checkbox, and a submit button. You can view a screenshot of it here: https://i.sstatic.net/nE1FY.png The terms of use a ...

What is the best way to retrieve the data submitted in the Input field by using Ajax?

One feature I'm working on involves an input field within a form where users can update their name by clicking a button. The goal is to capture this change in the input field using Ajax and update it accordingly. Here's the HTML code snippet: & ...