Challenges faced with JavaScript Ajax functionality

Currently, I am developing a custom HTTP client using JavaScript. Although my code appears to be correct, I keep receiving 404 errors for my requests. This code is being executed on a NodeJS (ExpressJS) server that includes a handler as shown below:

app.post('/api/update', (req, res) => {
    res.send(req.body);
});

Below is the JavaScript code I am using:

const customHTTPClient = (method, url, post) => {
  return new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);

    xhr.onload = () => {
      const statusText = xhr.statusText || '';

      const response = ('response' in xhr) ? xhr.response : xhr.responseText;

      let status = xhr.status === 1223 ? 204 : xhr.status;

      if (status === 0) {
        status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
      }
      try {
        return resolve(JSON.parse(response));
      } catch (error) {
        return resolve(response);
      }
    };

    xhr.onerror = () => reject('Error');
    xhr.ontimeout = () => reject('Timeout');
    xhr.onabort = () => reject('Abort');

    xhr.send(JSON.stringify(post) || null);
  });
};


customHTTPClient('post', '/api/update', defaultData).then(response => {
  css.value = response.data;
  console.log(response);
}, error => {
  console.error(error);
});

IMPORTANT: defaultData is an Object

Answer №1

It appears that you overlooked including the Content-type header in your code.

const CustomHTTPClient = (method, url, data) => {
  return new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);

    // ADD THIS LINE
    xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

    xhr.onload = () => {
      const statusText = xhr.statusText || '';

      const response = ('response' in xhr) ? xhr.response : xhr.responseText;

      let status = xhr.status === 1223 ? 204 : xhr.status;

      if (status === 0) {
        status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
      }
      try {
        return resolve(JSON.parse(response));
      } catch (error) {
        return resolve(response);
      }
    };

    xhr.onerror = () => reject('Error');
    xhr.ontimeout = () => reject('Timeout');
    xhr.onabort = () => reject('Abort');

    xhr.send(JSON.stringify(data) || null);
  });
};


CustomHTTPClient('post', '/api/update', defaultData).then(response => {
  css.value = response.data;
  console.log(response);
}, error => {
  console.error(error);
});

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

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

Strange behavior of Backbone.js save

After creating a new model (msg), I proceed to save it using the following code snippet: msg.save({}, {success: this.createSuccess, error: function(model, response){ console.log('nay', response); }}); Despite receiving a status: 200 and statu ...

Transform the text color of a table generated by a v-for loop

I have a Vue.js setup to exhibit a collection of JSON data which consists mainly of numbers. These numbers are displayed in a table format, with one minor issue - if the number happens to be negative, the text color of its cell needs to be red. <table& ...

Dividing a pair of CSS stylesheets on a single HTML page

Currently, I am working on a HTML page that includes multiple javascripts and css files in the header section. <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" /> In order to make the website mobile-friendly, I s ...

Configuring a custom domain for a Rust service on Clever Cloud: A step-by-step guide

After successfully deploying my Rust service to the Clever Cloud platform and testing it on PROD and localhost, I am now facing the challenge of binding my custom domain with the deployed service. I would like to eliminate the need for using the lengthy C ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

Development mode causing sluggish asset compilation

I am facing an issue with a large rails application that has hundreds of coffee script files. Whenever I make a small change in a coffee script file or switch branches, the entire assets need to be precompiled, causing a significant delay in loading the p ...

"Transferring a Ruby hash containing objects as keys to JavaScript on the front end as a Map object: a step-by-step

While Javascript does not natively support objects as object keys, the Map object offers a solution. My query is, how can an object like this be transmitted easily from the backend to the frontend? def test_controller object = {"a"=>1," ...

Continuously monitor and track the advancements within the update panel

Within an update panel, I have two buttons that need to trigger the update progress and display a .gif image on each button click. When Button1 is clicked, only its associated update progress should be shown while the other one remains invisible. ...

Exclude the CSS file from all elements except for the ones that are being appended to a specific div

Imagine you have a document with a CSS file that applies to all elements on the page. Is there a way to selectively remove or add styles from this file so they only affect a specific div and not the entire document? ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

Using an if/else statement in a Jade Template to conditionally remove a select option

I'm a beginner with Jade and I've been assigned to add a select option to a webpage. Everything is working well, except for when the drop-down list is empty and the page is refreshed, an empty option element is created. I want to find a way to re ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

Encountering a 404 error while sending a session ID in a Post request using AngularJS

My services are hosted on a remote server, and I am consuming these services in a local AngularJS app. Everything works fine with REST requests that do not require a SessionID in the header. However, when I add the Session ID in the header, it does not wor ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Choose an option from the menu and store it in the database for future reference

Currently, I am working on a website project for a client using Codeigniter 3 HMVC style. One of the requirements is to implement a feature where logged-in users can choose their preferred news topics. For instance, if a user selects "Juventus," they will ...

The correct method for accessing descendants in THREE.js in the latest version, r68

As of the release r68, the getDescendants() method has been removed from the THREE.Object3D API. How should we now achieve the same functionality without any warning message being provided? ...

Creating a visually appealing label by customizing it according to the child div

Can the label be styled based on whether the input is checked or not using CSS, or do I have to use JavaScript? <label class="filterButton"> <input name="RunandDrive" type="checkbox" value="1"> </label> ...

Learn how to verify changing form inputs with Vue watchers. The challenge of numbers

Currently, I am working on a sum application and encountering some challenges with input validations. I have implemented Watcher to handle the validations, and I am exploring the possibility of adding sound and color feedback for accurate validation. Repo ...

Introduce a pause using the raycaster function

When my raycaster intersects an object for 2 seconds, I want to update the object's texture. I attempted to use the clock function, but I am unsure of how to properly implement it. var clock = new THREE.Clock(); clock.autoStart = true; var inters ...