Exploring Strategies for Optimizing HTTP Error Messages

My current challenge involves sending a JSON-encoded data string to a remote machine via AJAX. Every time I attempt to transmit the data string, one of two error messages emerges:

XMLHttpRequest cannot load http://10.1.0.139:8000/. 
No 'Access-Control-Allow-Origin' header is present on 
the requested resource. Origin 'http://localhost' is 
therefore not allowed access.

This message occurs when the remote machine is operational and accepting connections. Despite this error, my code successfully sends the correct data string to the remote machine.

POST http://10.1.0.139:8000/ net::ERR_CONNECTION_REFUSED

The second message appears when the remote machine is turned off or doesn't have its own server running to accept incoming requests and connections.

My main issue lies in distinguishing between these two error messages. Traditional AJAX callbacks like error() or fail() are not effective since there will always be an error, even if the HTTP status 200 confirms that everything is functioning correctly (as shown by the first error).

Is there any way to implement a pseudo command that states 'IF I FAIL TO CONNECT TO REMOTE MACHINE, THEN...'

EDIT

Upon further observation, my remote machine fails to display incoming connections made from Internet Explorer, instead showing the following:

XMLHttpRequest: Network Error 0x2efd,   
Could not complete the operation due to error 00002efd.

Answer №1

Utilize the XMLHttpRequest timeout feature

let xhr = new window.XMLHttpRequest();
let requestData = 'x=1';
xhr.open('POST', 'http://10.1.0.139:8000/');
xhr.timeout = 5000;
xhr.addEventListener('timeout', function(event) {
    // handle server timeout
    console.log('request timed out');
    console.error(event);
});
xhr.addEventListener('error', function(event) {
    // handle CORS error or other errors
    console.log('an error occurred');
    console.error(event);
});
xhr.addEventListener('load', function(event) {
    // handle successful response
    console.log('request successful');
    console.info(event);
});
xhr.send(requestData);

This will result in an error if there is a CORS issue, and a timeout if the server is unresponsive

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

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Is it possible to bind computed values in Ember using .properties(...) with ember-model?

I'm attempting to utilize the .property('key') syntax in order to update a computed value within my model. The structure of my model is as follows: App.Camera = Em.Model.extend({ id: attr(), uid: attr(), name: attr(), type: ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...

I'm having trouble mocking the image import correctly when trying to pass a test using jest with next.js. Why am I encountering this error?

Having some trouble passing a test with Jest in Next.js. The imported image doesn't seem to be mocked by Jest, and I can't figure out what's missing. Followed all the steps in the Next.js documentation. The fileMock.js is located at <rou ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

"Compactly condensing" an abundance of boolean values in JSON through manual effort

We are dealing with a data model that consists of 600 boolean values per entity. This entire dataset needs to be transmitted from a node.js backend to an Angular frontend via JSON. Considering the internal nature of this API (not public), our primary focu ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

Leveraging an array retrieved through JQuery AJAX for auto-complete data in materializecss

I am delving into materializecss for the first time, aiming to enhance its auto complete feature by incorporating an array of options obtained from a database. Unfortunately, my attempts have not been successful. After scouring through Stack Overflow and o ...

Setting a default year in a React datepicker: A step-by-step guide

I'm currently working with the react datepicker and I want to specify a default year (1990) when the calendar is opened. I've tried using the 'date' and 'initialDate' props, but they don't seem to be working. Below is th ...

specialized html elements within data-ng-options

I have a code snippet where I am populating select options from a controller using data-ng-options. However, I would also like to include an icon with each option. For example, I want to append <span class="fa fa-plus"></span> at the end of e ...

What strategies can be implemented to maximize memory and CPU efficiency in NodeJS and Express?

My Node app, running on Express, utilizes a web scraping tool to gather and analyze data. While NodeJS is praised for its scalability and ability to handle numerous concurrent connections, I've noticed some difficulties when operating a web scraper t ...

How does bodyParser determine the specific view to populate in req.body?

Within the following code snippet, a sole view named fruitPicker.html is utilized to prevent any confusion in terms of how bodyParser should populate req.body app.js: var express = require('express') , app = express() , cons = require(&apos ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

Displaying JavaScript Array Elements in an Aligned Table Format

Unfortunately, I accidentally deleted my previous post and now need to repost it. I have a code that is functioning well, thanks to the great help I received here. However, the output of the array players is not neatly aligned with each other in a table f ...

How can milliseconds be formatted to a date within a map in a React component?

After receiving an array of objects from the backend (Firebase) with properties url:string and timestamp{seconds: number, nanoseconds: number}, I attempted to use a map function to display all the pictures along with their upload date. However, I encounter ...

Merge arrays in map function based on label and aggregate information

In my possession is an array filled with data from various streaming channels, categorized by shift (Morning and Afternoon). I dedicated the night to experimenting with different functions like reduce, but unfortunately, I hit a wall and couldn't gra ...

What is the purpose of importing React from "react" in a .jsx file? Is there any distinction between the .jsx and .js extensions?

Typically, we use it to write JSX syntax within .js files. ...however, since I've already specified the extension as .jsx, why do we still need to import the react module? I've attempted to find the answer, but it remains unclear in all my resea ...

In Vue.js, leverage the power of slots to access content from deeply nested child components

Recently, I came across this example: This child component serves as the foundation for all the components that follow. <template> <div class="content-box"> <div class="boxtitlecontainer titleColor"> <slot name="title"> ...