Error xhr request timed out

I could not find a report of a similar problem as the subject. Basically what is the System -> Startup page supposed to do, and what would contribute to the indicated error, "XHR request ti...

I didn’t notice this before. But it seems like the command

ubus call luci getInitList

Actually causes the init scripts to run. In particular in my rc.local I have commands to ‘mount’ a USB memory device as a file system structured device.

Hence the first few lines of the following output are from that process.

The question I have is, is it true that when the browser access the the System -> startup page, it invokes the scripts associated with the init.d and rc.local?

—- output —-
root@RaptorXR:/# ubus call luci getInitList
Mounting /dev/sda1 /video/lib
[ 5444.427158] [EXFAT] trying to mount…
[ 5444.431930] [EXFAT] mounted successfully
Mounting /dev/sda1 /video/lib
mount: mounting /dev/sda1 on /video/lib failed: Resource busy
{
«stunnel»: {
«index»: 90,
«enabled»: true
},
«gpio_switch»: {
«index»: 94,
«enabled»: true
},
«odhcpd»: {
«index»: 35,
«enabled»: true
},
«rpcd»: {
«index»: 12,
«enabled»: true
},
«dropbear»: {
«index»: 19,
«enabled»: true
},
«rsyncd»: {
«index»: 90,
«enabled»: true
},
«led»: {
«index»: 96,
«enabled»: true
},
«ucitrack»: {
«index»: 80,
«enabled»: true
},
«cron»: {
«index»: 50,
«enabled»: true
},
«fwknopd»: {
«index»: 95,
«enabled»: true
},
«collectd»: {
«index»: 80,
«enabled»: true
},
«snmpd»: {
«index»: 50,
«enabled»: true
},
«uhttpd»: {
«index»: 50,
«enabled»: true
},
«done»: {
«index»: 95,
«enabled»: true
},
«system»: {
«index»: 10,
«enabled»: true
},
«lm-sensors»: {
«index»: 28,
«enabled»: true
},
«gpsd»: {
«index»: 50,
«enabled»: true
},
«ddns»: {
«index»: 95,
«enabled»: true
},
«luci_statistics»: {
«index»: 79,
«enabled»: true
},
«qos»: {
«index»: 50,
«enabled»: true
},
«WSRadioDown»: {
«index»: 255,
«enabled»: false
},
«vsftpd»: {
«index»: 50,
«enabled»: true
},
«lighttpd»: {
«index»: 50,
«enabled»: true
},
«umount»: {
«index»: 255,
«enabled»: false
},
«urngd»: {
«index»: 0,
«enabled»: true
},
«sysfsutils»: {
«index»: 11,
«enabled»: true
},
«sysntpd»: {
«index»: 98,
«enabled»: true
},
«urandom_seed»: {
«index»: 99,
«enabled»: true
},
«network»: {
«index»: 20,
«enabled»: true
},
«atd»: {
«index»: 50,
«enabled»: true
},
«conntrackd»: {
«index»: 21,
«enabled»: true
},
«syslog-ng»: {
«index»: 50,
«enabled»: true
},
«diagBoot»: {
«index»: 255,
«enabled»: true
},
«log»: {
«index»: 12,
«enabled»: true
},
«snort»: {
«index»: 90,
«enabled»: true
},
«sysfixtime»: {
«index»: 0,
«enabled»: true
},
«firewall»: {
«index»: 19,
«enabled»: true
},
«sysctl»: {
«index»: 11,
«enabled»: true
},
«boot»: {
«index»: 10,
«enabled»: true
},
«dnsmasq»: {
«index»: 19,
«enabled»: true
},
«relayd»: {
«index»: 80,
«enabled»: true
},
«lvm2»: {
«index»: 15,
«enabled»: true
}
}
root@RaptorXR:/#

Содержание

  1. The ‘startup’ page using the OpenWRT Luci theme, results in «XHR request timed out» #4090
  2. Comments
  3. How to make HTTP requests using XMLHttpRequest (XHR)
  4. Basic XHR Request
  5. xhr.open() Method
  6. xhr.send() Method
  7. XHR Events
  8. Request Timeout
  9. Response Type
  10. Request States ( xhr.readyState )
  11. Aborting Request
  12. Synchronous Requests
  13. HTTP Headers
  14. XHR POST Request
  15. XHR POST Request with with application/x-www-form-urlencoded
  16. XHR POST Request with JSON Data
  17. Cross-Origin Requests & Cookies
  18. XHR vs. jQuery
  19. XHR vs. Fetch API

The ‘startup’ page using the OpenWRT Luci theme, results in «XHR request timed out» #4090

I could not find a report of a similar problem as the subject.

Basically what is the System -> Startup page supposed to do, and what would contribute to the indicated error, «XHR request timed out», and a continual ‘loading. ‘ message.

Thanks
John Clark.

The text was updated successfully, but these errors were encountered:

Here’s something like this is when you manually stop loading the page

A broken init script could cause it. Please provide the current output of ls -lh /etc/init.d/

What is meant by ‘a broken init script’?

Here’s the output of the listing on /etc/init.d

root@RaptorXR-10:/www# ls -lh /etc/init.d/
-rwxr-xr-x 1 root root 64 Nov 22 17:53 WSRadioDown
-rwxr-xr-x 1 root root 692 Nov 22 17:53 atd
-rwxr-xr-x 1 root root 1.4K Nov 22 17:53 boot
-rwxr-xr-x 1 root root 7.9K Nov 22 17:53 collectd
-rwxr-xr-x 1 root root 324 Nov 22 17:53 conntrackd
-rwxr-xr-x 1 root root 821 Nov 22 17:53 cron
-rwxr-xr-x 1 root root 367 Nov 22 17:53 ddns
-rwxr-xr-x 1 root root 340 Nov 22 17:53 diagBoot
-rwxr-xr-x 1 root root 29.4K Nov 22 17:53 dnsmasq
-rwxr-xr-x 1 root root 255 Nov 22 17:53 done
-rwxr-xr-x 1 root root 5.8K Nov 22 17:53 dropbear
-rwxr-xr-x 1 root root 997 Nov 22 17:53 firewall
-rwxr-xr-x 1 root root 5.6K Nov 22 17:53 fwknopd
-rwxr-xr-x 1 root root 1013 Nov 22 17:53 gpio_switch
-rwxr-xr-x 1 root root 841 Nov 22 17:53 gpsd
-rwxr-xr-x 1 root root 3.4K Nov 22 17:53 led
-rwxr-xr-x 1 root root 685 Nov 22 17:53 lighttpd
-rwxr-xr-x 1 root root 214 Nov 22 17:53 lm-sensors
-rwxr-xr-x 1 root root 2.3K Nov 22 17:53 log
-rwxr-xr-x 1 root root 652 Nov 22 17:53 luci_statistics
-rwxr-xr-x 1 root root 323 Nov 22 17:53 lvm2
-rwxr-xr-x 1 root root 2.6K Nov 22 17:53 network
-rwxr-xr-x 1 root root 292 Nov 22 17:53 odhcpd
-rwxr-xr-x 1 root root 391 Nov 22 17:53 qos
-rwxr-xr-x 1 root root 2.3K Nov 22 17:53 relayd
-rwxr-xr-x 1 root root 368 Nov 22 17:53 rpcd
-rwxr-xr-x 1 root root 232 Nov 22 17:53 rsyncd
-rwxr-xr-x 1 root root 9.5K Nov 22 17:53 snmpd
-rwxr-xr-x 1 root root 749 Nov 22 17:53 snort
-rwxr-xr-x 1 root root 8.2K Nov 22 17:53 stunnel
-rwxr-xr-x 1 root root 1.2K Nov 22 17:53 sysctl
-rwxr-xr-x 1 root root 662 Nov 22 17:53 sysfixtime
-rwxr-xr-x 1 root root 1.2K Nov 22 17:53 sysfsutils
-rwxr-xr-x 1 root root 248 Nov 22 17:53 syslog-ng
-rwxr-xr-x 1 root root 2.1K Nov 22 17:53 sysntpd
-rwxr-xr-x 1 root root 986 Nov 22 17:53 system
-rwxr-xr-x 1 root root 1.3K Nov 22 17:53 ucitrack
-rwxr-xr-x 1 root root 5.3K Nov 22 17:53 uhttpd
-rwxr-xr-x 1 root root 125 Nov 22 17:53 umount
-rwxr-xr-x 1 root root 239 Nov 22 17:53 urandom_seed
-rwxr-xr-x 1 root root 220 Nov 22 17:53 urngd
-rwxr-xr-x 1 root root 195 Nov 22 17:53 vsftpd

Whats happens if you invoke ubus call luci getInitList via SSH?

While it does take a little time to return with a list, it does return a list. The web page, just hangs.

—- output of root@RaptorXR-10:/www# ubus call luci getInitList

root@RaptorXR-10:/www# ubus call luci getInitList
<
«stunnel»: <
«index»: 90,
«enabled»: true
>,
«gpio_switch»: <
«index»: 94,
«enabled»: true
>,
«odhcpd»: <
«index»: 35,
«enabled»: true
>,
«rpcd»: <
«index»: 12,
«enabled»: true
>,
«dropbear»: <
«index»: 19,
«enabled»: true
>,
«rsyncd»: <
«index»: 90,
«enabled»: true
>,
«led»: <
«index»: 96,
«enabled»: true
>,
«ucitrack»: <
«index»: 80,
«enabled»: true
>,
«cron»: <
«index»: 50,
«enabled»: true
>,
«fwknopd»: <
«index»: 95,
«enabled»: true
>,
«collectd»: <
«index»: 80,
«enabled»: true
>,
«snmpd»: <
«index»: 50,
«enabled»: true
>,
«uhttpd»: <
«index»: 50,
«enabled»: true
>,
«done»: <
«index»: 95,
«enabled»: true
>,
«system»: <
«index»: 10,
«enabled»: true
>,
«lm-sensors»: <
«index»: 28,
«enabled»: true
>,
«gpsd»: <
«index»: 50,
«enabled»: true
>,
«ddns»: <
«index»: 95,
«enabled»: true
>,
«luci_statistics»: <
«index»: 79,
«enabled»: true
>,
«qos»: <
«index»: 50,
«enabled»: true
>,
«WSRadioDown»: <
«index»: 255,
«enabled»: false
>,
«vsftpd»: <
«index»: 50,
«enabled»: true
>,
«lighttpd»: <
«index»: 50,
«enabled»: true
>,
«umount»: <
«index»: 255,
«enabled»: false
>,
«urngd»: <
«index»: 0,
«enabled»: true
>,
«sysfsutils»: <
«index»: 11,
«enabled»: true
>,
«sysntpd»: <
«index»: 98,
«enabled»: true
>,
«urandom_seed»: <
«index»: 99,
«enabled»: true
>,
«network»: <
«index»: 20,
«enabled»: true
>,
«atd»: <
«index»: 50,
«enabled»: true
>,
«conntrackd»: <
«index»: 21,
«enabled»: true
>,
«syslog-ng»: <
«index»: 50,
«enabled»: true
>,
«diagBoot»: <
«index»: 255,
«enabled»: true
>,
«log»: <
«index»: 12,
«enabled»: true
>,
«snort»: <
«index»: 90,
«enabled»: true
>,
«sysfixtime»: <
«index»: 0,
«enabled»: true
>,
«firewall»: <
«index»: 19,
«enabled»: true
>,
«sysctl»: <
«index»: 11,
«enabled»: true
>,
«boot»: <
«index»: 10,
«enabled»: true
>,
«dnsmasq»: <
«index»: 19,
«enabled»: true
>,
«relayd»: <
«index»: 80,
«enabled»: true
>,
«lvm2»: <
«index»: 15,
«enabled»: true
>
>

Can you check how long it takes to return that list? Retry with time ubus call luci getInitList

I’ll not post the resulting JSON list. but here’s the time results:

real 0m 22.89s
user 0m 0.00s
sys 0m 0.00s

So, about 23 seconds to return a response. Is there some timeout value that is set to low? And if so, how to change that?

I didn’t notice this before. But it seems like the command

ubus call luci getInitList

Actually causes the init scripts to run. In particular in my rc.local I have commands to ‘mount’ a USB memory device as a file system structured device.

Hence the first few lines of the following output are from that process.

The question I have is, is it true that when the browser access the the System -> startup page, it invokes the scripts associated with the init.d and rc.local?

—- output —-
root@RaptorXR:/# ubus call luci getInitList
Mounting /dev/sda1 /video/lib
[ 5444.427158] [EXFAT] trying to mount.
[ 5444.431930] [EXFAT] mounted successfully
Mounting /dev/sda1 /video/lib
mount: mounting /dev/sda1 on /video/lib failed: Resource busy
<
«stunnel»: <
«index»: 90,
«enabled»: true
>,
«gpio_switch»: <
«index»: 94,
«enabled»: true
>,
«odhcpd»: <
«index»: 35,
«enabled»: true
>,
«rpcd»: <
«index»: 12,
«enabled»: true
>,
«dropbear»: <
«index»: 19,
«enabled»: true
>,
«rsyncd»: <
«index»: 90,
«enabled»: true
>,
«led»: <
«index»: 96,
«enabled»: true
>,
«ucitrack»: <
«index»: 80,
«enabled»: true
>,
«cron»: <
«index»: 50,
«enabled»: true
>,
«fwknopd»: <
«index»: 95,
«enabled»: true
>,
«collectd»: <
«index»: 80,
«enabled»: true
>,
«snmpd»: <
«index»: 50,
«enabled»: true
>,
«uhttpd»: <
«index»: 50,
«enabled»: true
>,
«done»: <
«index»: 95,
«enabled»: true
>,
«system»: <
«index»: 10,
«enabled»: true
>,
«lm-sensors»: <
«index»: 28,
«enabled»: true
>,
«gpsd»: <
«index»: 50,
«enabled»: true
>,
«ddns»: <
«index»: 95,
«enabled»: true
>,
«luci_statistics»: <
«index»: 79,
«enabled»: true
>,
«qos»: <
«index»: 50,
«enabled»: true
>,
«WSRadioDown»: <
«index»: 255,
«enabled»: false
>,
«vsftpd»: <
«index»: 50,
«enabled»: true
>,
«lighttpd»: <
«index»: 50,
«enabled»: true
>,
«umount»: <
«index»: 255,
«enabled»: false
>,
«urngd»: <
«index»: 0,
«enabled»: true
>,
«sysfsutils»: <
«index»: 11,
«enabled»: true
>,
«sysntpd»: <
«index»: 98,
«enabled»: true
>,
«urandom_seed»: <
«index»: 99,
«enabled»: true
>,
«network»: <
«index»: 20,
«enabled»: true
>,
«atd»: <
«index»: 50,
«enabled»: true
>,
«conntrackd»: <
«index»: 21,
«enabled»: true
>,
«syslog-ng»: <
«index»: 50,
«enabled»: true
>,
«diagBoot»: <
«index»: 255,
«enabled»: true
>,
«log»: <
«index»: 12,
«enabled»: true
>,
«snort»: <
«index»: 90,
«enabled»: true
>,
«sysfixtime»: <
«index»: 0,
«enabled»: true
>,
«firewall»: <
«index»: 19,
«enabled»: true
>,
«sysctl»: <
«index»: 11,
«enabled»: true
>,
«boot»: <
«index»: 10,
«enabled»: true
>,
«dnsmasq»: <
«index»: 19,
«enabled»: true
>,
«relayd»: <
«index»: 80,
«enabled»: true
>,
«lvm2»: <
«index»: 15,
«enabled»: true
>
>
root@RaptorXR:/#

It sources each script in /etc/init.d/ to extract START and STOP variables. Furthermore it invokes /etc/init.d/xxx enabled for each script to determine whether it is enabled.

Properly written init scripts should do nothing when sourced or called with enabled as argument. I suspect there’s one or more custom init scripts (or maybe init scripts by packages) which behave differently, causing the long delay.

That seems to be it. I guess I had thought that the entries in the webpage would not have invoked the scripts in init.d/* themselves, but matched up the existence of an entry in rc.d/* with what was found in init.d/*.

So my custom scripts which have to be run before rc.local, were just the shell commands required, and not put into such things as ‘boot <>‘ etc.

Closing this as it was caused by changes unrelated to LuCI.

Источник

How to make HTTP requests using XMLHttpRequest (XHR)

XMLHttpRequest is a built-in browser object in all modern browsers that can be used to make HTTP requests in JavaScript to exchange data between the web browser and the server.

Despite the word «XML» in its name, XMLHttpRequest can be used to retrieve any kind of data and not just XML. We can use it to upload/download files, submit form data, track progress, and much more.

Basic XHR Request

To send an HTTP request using XHR, create an XMLHttpRequest object, open a connection to the URL, and send the request. Once the request completes, the object will contain information such as the response body and the HTTP status code.

Let’s use JSONPlaceholder to test REST API to send a GET request using XHR:

The xhr.onload event only works in modern browsers (IE10+, Firefox, Chrome, Safari). If you want to support old browsers, use the xhr.onreadystatechange event instead.

xhr.open() Method

In the example above, we passed the HTTP method and a URL to the request to the open() method. This method is normally called right after new XMLHttpRequest() . We can use this method to specify the main parameters of the request:

Here is the syntax of this method:

  • method — HTTP request method. It can be GET , POST , DELETE , PUT , etc.
  • URL — The URL to request, a string or a URL object
  • asnyc — Specify whether the request should be made asynchronously or not. The default value is true
  • username & password — Credentials for basic HTTP authentication

The open() method does not open the connection to the URL. It only configures the HTTP request.

xhr.send() Method

The send() method opens the network connection and sends the request to the server. It takes an optional body parameter that contains the request body. For request methods like GET you do not need to pass the body parameter.

XHR Events

The three most widely used XHR events are the following:

  • load — This event is invoked when the result is ready. It is equivalent to the xhr.onreadystatechange event with xhr.readyState == 4 .
  • error — This event is fired when the request is failed due to a network down or invalid URL.
  • progress — This event is triggered periodically during the response download. It can be used to report progress for large network requests.

Request Timeout

You can easily configure the request timeout by specifying the time in milliseconds:

xhr.responseURL property returns the final URL of an XMLHttpRequest instance after following all redirects. This is the only way to retrieve the Location header.

Response Type

We can use the xhr.responseType property to set the expected response format:

  • Empty (default) or text — plain text
  • json — parsed JSON
  • blob — binary data Blob
  • document — XML document
  • arraybuffer — ArrayBuffer for binary data

Let’s call a RESTful API to get the response as JSON:

Request States ( xhr.readyState )

The XMLHttpRequest object changes state as the request progresses. We can access the current state using the xhr.readyState property.

The states are:

  • UNSENT (0) — The initial state
  • OPENED (1) — The request begins
  • HEADERS_RECEIVED (2) — The HTTP headers received
  • LOADING (3) — Response is loading
  • DONE (4) — The request is completed

We can track the request state by using the onreadystatechange event:

Aborting Request

We can easily abort an XHR request anytime by calling the abort() method on the xhr object:

Synchronous Requests

By default, XHR makes an asynchronous request which is good for performance. But if you want to make an explicit synchronous request, just pass false as 3rd argument to the open() method. It will pause the JavaScript execution at send() and resume when the response is available:

Be careful! Chrome display the following warning for synchronous XHR request: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects on the end user’s experience.

XMLHttpRequest allows us to set request headers and read response headers. We can set the request Content-Type & Accept headers by calling setRequestHeader() method on the xhr object:

Similarly, if you want to read the response headers (except Set-Cookie ), call get response header() on the xhr object:

Want to get response headers at once? Use getAllResponseHeaders() instead:

XHR POST Request

There are two ways to make a POST HTTP request using XMLHttpRequest : URL encoded form-data and FormData API.

XHR POST Request with with application/x-www-form-urlencoded

The following example demonstrates how you can make a POST request with URL-encoded form data:

XHR POST Request with JSON Data

To make an XHR POST request with JSON data, you must the JSON data into a string using JSON.stringify() and set the content-type header to application/json :

Cross-Origin Requests & Cookies

XMLHttpRequest can send cross-origin requests, but it is subjected to special security measures. To request a resource from a different server, the server must explicitly support this using CORS (Cross-Origin Resource Sharing).

Just like Fetch API, XHR does not send cookies and HTTP authorization to another origin. To send cookies, you can use the withCredentials property of the xhr object:

XHR vs. jQuery

jQuery wrapper methods like $.ajax() use XHR under the hood to provide a higher level of abstraction. Using jQuery, we can translate the above code into just a few lines:

XHR vs. Fetch API

The Fetch API is a promise-based modern alternative to XHR. It is clean, easier to understand, and massively used in PWA Service Workers.

The XHR example above can be converted to a much simpler fetch() -based code that even automatically parses the returned JSON:

Read JavaScript Fetch API guide to understand how you can use Fetch API to request network resources with just a few lines of code.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

Источник

XMLHttpRequest is a built-in browser object in all modern browsers that can be used to make HTTP requests in JavaScript to exchange data between the web browser and the server.

Despite the word «XML» in its name, XMLHttpRequest can be used to retrieve any kind of data and not just XML. We can use it to upload/download files, submit form data, track progress, and much more.

Basic XHR Request

To send an HTTP request using XHR, create an XMLHttpRequest object, open a connection to the URL, and send the request. Once the request completes, the object will contain information such as the response body and the HTTP status code.

Let’s use JSONPlaceholder to test REST API to send a GET request using XHR:

// create an XHR object
const xhr = new XMLHttpRequest()

// listen for `onload` event
xhr.onload = () => {
  // process response
  if (xhr.status == 200) {
    // parse JSON data
    console.log(JSON.parse(xhr.response))
  } else {
    console.error('Error!')
  }
}

// create a `GET` request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')

// send request
xhr.send()

The xhr.onload event only works in modern browsers (IE10+, Firefox, Chrome, Safari). If you want to support old browsers, use the xhr.onreadystatechange event instead.

xhr.open() Method

In the example above, we passed the HTTP method and a URL to the request to the open() method. This method is normally called right after new XMLHttpRequest(). We can use this method to specify the main parameters of the request:

Here is the syntax of this method:

xhr.open(method, URL, [async, user, password])
  • method — HTTP request method. It can be GET, POST, DELETE, PUT, etc.
  • URL — The URL to request, a string or a URL object
  • asnyc — Specify whether the request should be made asynchronously or not. The default value is true
  • username & password — Credentials for basic HTTP authentication

The open() method does not open the connection to the URL. It only configures the HTTP request.

xhr.send() Method

xhr.send([body])

The send() method opens the network connection and sends the request to the server. It takes an optional body parameter that contains the request body. For request methods like GET you do not need to pass the body parameter.

XHR Events

The three most widely used XHR events are the following:

  • load — This event is invoked when the result is ready. It is equivalent to the xhr.onreadystatechange event with xhr.readyState == 4.
  • error — This event is fired when the request is failed due to a network down or invalid URL.
  • progress — This event is triggered periodically during the response download. It can be used to report progress for large network requests.
// listen for `load` event
xhr.onload = () => {
  console.log(`Data Loaded: ${xhr.status} ${xhr.response}`)
}

// listen for `error` event
xhr.onerror = () => {
  console.error('Request failed.')
}

// listen for `progress` event
xhr.onprogress = event => {
  // event.loaded returns how many bytes are downloaded
  // event.total returns the total number of bytes
  // event.total is only available if server sends `Content-Length` header
  console.log(`Downloaded ${event.loaded} of ${event.total}`)
}

Request Timeout

You can easily configure the request timeout by specifying the time in milliseconds:

// set timeout
xhr.timeout = 5000 // 5 seconds

// listen for `timeout` event
xhr.ontimeout = () => console.log('Request timeout.', xhr.responseURL)

xhr.responseURL property returns the final URL of an XMLHttpRequest instance after following all redirects. This is the only way to retrieve the Location header.

Response Type

We can use the xhr.responseType property to set the expected response format:

  • Empty (default) or text — plain text
  • json — parsed JSON
  • blob — binary data Blob
  • document — XML document
  • arraybufferArrayBuffer for binary data

Let’s call a RESTful API to get the response as JSON:

const xhr = new XMLHttpRequest()

xhr.open('GET', 'https://api.jsonbin.io/b/5d5076e01ec3937ed4d05eab/1')

// set response format
xhr.responseType = 'json'

xhr.send()

xhr.onload = () => {
  // get JSON response
  const user = xhr.response

  // log details
  console.log(user.name) // John Doe
  console.log(user.email) // john.doe@example.com
  console.log(user.website) // http://example.com
}

Request States (xhr.readyState)

The XMLHttpRequest object changes state as the request progresses. We can access the current state using the xhr.readyState property.

The states are:

  • UNSENT (0) — The initial state
  • OPENED (1) — The request begins
  • HEADERS_RECEIVED (2) — The HTTP headers received
  • LOADING (3) — Response is loading
  • DONE (4) — The request is completed

We can track the request state by using the onreadystatechange event:

xhr.onreadystatechange = function () {
  if (xhr.readyState == 1) {
    console.log('Request started.')
  }

  if (xhr.readyState == 2) {
    console.log('Headers received.')
  }

  if (xhr.readyState == 3) {
    console.log('Data loading..!')
  }
  if (xhr.readyState == 4) {
    console.log('Request ended.')
  }
}

Aborting Request

We can easily abort an XHR request anytime by calling the abort() method on the xhr object:

xhr.abort() // cancel request

Synchronous Requests

By default, XHR makes an asynchronous request which is good for performance. But if you want to make an explicit synchronous request, just pass false as 3rd argument to the open() method. It will pause the JavaScript execution at send() and resume when the response is available:

xhr.open('GET', 'https://api.jsonbin.io/b/5d5076e01ec3937ed4d05eab/1', false)

Be careful! Chrome display the following warning for synchronous XHR request: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects on the end user’s experience.

XMLHttpRequest allows us to set request headers and read response headers. We can set the request Content-Type & Accept headers by calling setRequestHeader() method on the xhr object:

// set request headers
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.setRequestHeader('Accept', '*/*') // accept all

Similarly, if you want to read the response headers (except Set-Cookie), call get response header() on the xhr object:

// read response headers
xhr.getResponseHeader('Content-Type')
xhr.getResponseHeader('Cache-Control')

Want to get response headers at once? Use getAllResponseHeaders() instead:

xhr.getAllResponseHeaders()

XHR POST Request

There are two ways to make a POST HTTP request using XMLHttpRequest: URL encoded form-data and FormData API.

XHR POST Request with with application/x-www-form-urlencoded

The following example demonstrates how you can make a POST request with URL-encoded form data:

const xhr = new XMLHttpRequest()

// configure a `POST` request
xhr.open('POST', '/login')

// prepare form data
let params = 'username=attacomsian&password=123456'

// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

// pass `params` to `send()` method
xhr.send(params)

// listen for `load` event
xhr.onload = () => {
  console.log(xhr.responseText)
}

XHR POST Request with JSON Data

To make an XHR POST request with JSON data, you must the JSON data into a string using JSON.stringify() and set the content-type header to application/json:

const xhr = new XMLHttpRequest()

// configure a `POST` request
xhr.open('POST', '/login')

// create a JSON object
const params = {
  username: 'attacomsian',
  password: '123456'
}

// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json')

// pass `params` to `send()` method
xhr.send(JSON.stringify(params))

// listen for `load` event
xhr.onload = () => {
  console.log(xhr.responseText)
}

Cross-Origin Requests & Cookies

XMLHttpRequest can send cross-origin requests, but it is subjected to special security measures. To request a resource from a different server, the server must explicitly support this using CORS (Cross-Origin Resource Sharing).

Just like Fetch API, XHR does not send cookies and HTTP authorization to another origin. To send cookies, you can use the withCredentials property of the xhr object:

xhr.withCredentials = true

XHR vs. jQuery

jQuery wrapper methods like $.ajax() use XHR under the hood to provide a higher level of abstraction. Using jQuery, we can translate the above code into just a few lines:

$.ajax('https://jsonplaceholder.typicode.com/users')
  .done(data => {
    console.log(data)
  })
  .fail(err => {
    console.error('Error:', err)
  })

XHR vs. Fetch API

The Fetch API is a promise-based modern alternative to XHR. It is clean, easier to understand, and massively used in PWA Service Workers.

The XHR example above can be converted to a much simpler fetch()-based code that even automatically parses the returned JSON:

fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error('Error:', err))

Read JavaScript Fetch API guide to understand how you can use Fetch API to request network resources with just a few lines of code.

✌️ Like this article? Follow me on
Twitter
and LinkedIn.
You can also subscribe to
RSS Feed.

Синхронные и асинхронные запросы

XMLHttpRequest поддерживает как синхронную, так и асинхронную связь. В целом, однако, асинхронные запросы следует предпочесть синхронным запросам из соображений производительности.

Синхронные запросы блокируют выполнение кода,что приводит к «замиранию» на экране и невосприимчивости пользователя.

Asynchronous request

Если вы используете асинхронный XMLHttpRequest , вы получите обратный вызов, когда данные будут получены. Это позволяет браузеру продолжать работать в обычном режиме, пока ваш запрос обрабатывается.

Пример:отправить файл в консольный журнал

Это простейшее использование асинхронного XMLHttpRequest .

var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null);

Строка 2 указывает true для своего третьего параметра, чтобы указать, что запрос должен обрабатываться асинхронно.

Строка 3 создает объект функции обработчика событий и назначает его атрибуту onload запроса . Этот обработчик смотрит на состояние readyState запроса, чтобы увидеть, завершена ли транзакция в строке 4; если это так и статус HTTP равен 200, обработчик выгружает полученное содержимое. Если произошла ошибка, отображается сообщение об ошибке.

На самом деле,15-я строка инициирует запрос.Обратный вызов вызывается всякий раз,когда состояние запроса меняется.

Пример:написание функции для чтения внешнего файла

В некоторых случаях вам необходимо прочитать много внешних файлов. Это стандартная функция, которая асинхронно использует объект XMLHttpRequest для переключения содержимого прочитанного файла на указанный прослушиватель.

function xhrSuccess() {
    this.callback.apply(this, this.arguments);
}

function xhrError() {
    console.error(this.statusText);
}

function loadFile(url, callback ) {
    var xhr = new XMLHttpRequest();
    xhr.callback = callback;
    xhr.arguments = Array.prototype.slice.call(arguments, 2);
    xhr.onload = xhrSuccess;
    xhr.onerror = xhrError;
    xhr.open("GET", url, true);
    xhr.send(null);
}

Usage:

function showMessage(message) {
    console.log(message + this.responseText);
}

loadFile("message.txt", showMessage, "New message!nn");

Подпись служебной функции loadFile объявляет (i) целевой URL-адрес для чтения (через HTTP-запрос GET), (ii) функцию, выполняемую при успешном завершении операции XHR, и (iii) произвольный список дополнительных аргументов, которые передаются через объект XHR (через свойство arguments ) в функцию обратного вызова успеха.

Строка 1 объявляет функцию, вызываемую после успешного завершения операции XHR. Он, в свою очередь, вызывает функцию обратного вызова, указанную при вызове функции loadFile (в данном случае функции showMessage ), которая была назначена свойству объекта XHR (строка 11). Дополнительные аргументы (если есть), предоставленные для вызова функции loadFile, «применяются» к запуску функции обратного вызова.

В пятой строке объявляется функция,вызываемая при неудачном завершении операции XHR.

Строка 11 хранит успешный обратный вызов, указанный как второй аргумент loadFile в свойстве callback объекта XHR .

Строка 12 loadFile массив аргументов, переданный при вызове loadFile . Начиная с третьего аргумента, все оставшиеся аргументы собираются, присваиваются свойству arguments переменной xhr , передаются в функцию обратного вызова успеха xhrSuccess . И в конечном итоге передаются функции обратного вызова (в данном случае showMessage ), которая вызывается функцией xhrSuccess .

Строка 15 указывает true для своего третьего параметра, чтобы указать, что запрос должен обрабатываться асинхронно.

Строка 16 фактически инициирует запрос.

Пример:использование таймаута

Вы можете использовать тайм-аут, чтобы ваш код не зависал в ожидании завершения чтения. Это делается путем установки значения свойства timeout в объекте XMLHttpRequest , как показано в приведенном ниже коде:

function loadFile(url, timeout, callback) {
    var args = Array.prototype.slice.call(arguments, 3);
    var xhr = new XMLHttpRequest();
    xhr.ontimeout = function () {
        console.error("The request for " + url + " timed out.");
    };
    xhr.onload = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                callback.apply(xhr, args);
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, true);
    xhr.timeout = timeout;
    xhr.send(null);
}

Обратите внимание на добавление кода для обработки события «timeout», установив обработчик ontimeout .

Usage:

function showMessage (message) {
    console.log(message + this.responseText);
}

loadFile("message.txt", 2000, showMessage, "New message!n");

Здесь мы указываем тайм-аут на 2000 мс.

Примечание: поддержка timeout была добавлена ​​в Gecko 12.0.

Synchronous request

Примечание. Начиная с Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0 и Edge 13, синхронные запросы в основном потоке устарели из-за их негативного влияния на взаимодействие с пользователем.

Синхронные запросы XHR часто вызывают зависания в Интернете.Но разработчики обычно не замечают этой проблемы,потому что зависание проявляется только при плохих сетевых условиях или когда удаленный сервер медленно отвечает.Синхронный XHR в настоящее время находится в состоянии устаревания.Разработчикам рекомендуется отказаться от синхронного API и вместо него использовать асинхронные запросы.

Все новые функции XHR, такие как timeout или abort , не разрешены для синхронного XHR. Это вызовет InvalidAccessError .

Пример:синхронный запрос HTTP

Данный пример демонстрирует,как сделать простой синхронный запрос.

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

Строка 3 отправляет запрос. null параметр указывает , что содержимое тела не требуется для GET запроса.

В пятой строке проверяется код статуса после завершения транзакции.Если результат 200 —HTTP «OK» —текстовое содержимое документа выводится на консоль.

Пример:Синхронный HTTP-запрос от рабочего устройства

Один из немногих случаев, когда синхронный запрос обычно не блокирует выполнение, — это использование XMLHttpRequest в Worker ‘е .

example.html (главная страница):

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
  var worker = new Worker("myTask.js");
  worker.onmessage = function(event) {
    alert("Worker said: " + event.data);
  };

  worker.postMessage("Hello");
</script>
</head>
<body></body>
</html>

myFile.txt (цель синхронного вызова XMLHttpRequest ):

Hello World!!

myTask.js ( Worker ):

self.onmessage = function (event) {
  if (event.data === "Hello") {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "myFile.txt", false);  
    xhr.send(null);
    self.postMessage(xhr.responseText);
  }
};

Примечание . Эффект асинхронный из-за использования Worker .

Этот шаблон может быть полезен, например, для взаимодействия с сервером в фоновом режиме или для предварительной загрузки содержимого. См. Примеры и подробности в разделе « Использование веб- воркеров».

Адаптация сценариев использования Sync XHR к API Beacon

В некоторых случаях синхронное использование XMLHttpRequest невозможно заменить, например, во время событий unload , beforeunload и pagehide . Вам следует рассмотреть возможность использования API fetch() с флагом keepalive . Когда fetch с keepalive недоступна, вы можете рассмотреть возможность использования API navigator.sendBeacon() , который может поддерживать эти варианты использования, но обычно обеспечивает хороший UX.

В следующем примере показан код теоретической аналитики, который пытается отправить данные на сервер с помощью синхронного XMLHttpRequest в обработчике выгрузки. Это приводит к задержке выгрузки страницы.

window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); 
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

Используя метод sendBeacon() , данные будут передаваться асинхронно на веб-сервер, когда пользовательский агент сможет это сделать, не задерживая выгрузку и не влияя на производительность следующей навигации.

В следующем примере показан шаблон кода теоретической аналитики, который отправляет данные на сервер с помощью sendBeacon() .

window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

See also

  • Using XMLHttpRequest
  • AJAX
  • navigator.sendBeacon


Web APIs

  • XMLHttpRequest.status

    Свойство XMLHttpRequest.status,доступное только для чтения,возвращает числовой код ответа.

  • XMLHttpRequest.statusText

    Доступное только для чтения свойство XMLHttpRequest.statusText возвращает DOMString, содержащее ответное сообщение, возвращенное сервером.

  • XMLHttpRequest.timeout

    Свойство XMLHttpRequest.timeout-это беззнаковое значение,представляющее количество миллисекунд,которое может пройти до автоматического завершения.

  • XMLHttpRequest:событие тайм-аута

    Событие таймаута срабатывает,когда прога завершается из-за истечения срока действия предустановки.

Do you want to fix XHR Failed error in VSCode?

At its heart, VSCode is based on the Electron framework. That means VSCode is basically a Chromium with code editing features developed on top of it. Whenever you get an error from VSCode, it’s most likely Chromium errors.

Users have reported that when they try to install an extension, especially behind a proxy network, they are presented with XHR Failed error. XHR Failed indicates that a few XHR requests may have been failed or interrupted while VSCode sends and receives extension information from the server.

In this article, we will discuss about possible fix for XHR Failed error in VSCode.

image-20210531161703991

Use a direct internet connection

If you’re behind a proxy network, try to disable it if you can.

Most of the time, the proxy network includes a firewall that may block VSCode requests to its servers.

In rare cases, the proxy network supports only HTTP or HTTPS protocol, leaving other communication through its network blocked, which can causes strange behavior in VSCode.

You can follow the instructions from Microsoft Forum to disable proxy on Windows 10. macOS users can consult this guide to do just that. Linux users should be able to disable proxy on their own, given that they are often more tech-savvy, but here’s a few tips on how to turn off proxy in Linux anyway.

Turn on automatic proxy detection

Chromium uses system proxy settings by default, so there’s a chance VSCode’s Chromium core does not recognize the proxy and cannot send/receive network data.

In order to turn on automatic proxy detection on Windows 10, follow HowToGeek guide.

automatic proxy detection Windows

Ignore certificate errors in VSCode

The actual implementation of the corporate proxy can vary from organization to organization, but there is one thing in common : they could all cause certificate errors.

Secure websites and applications use their own certificate to prevent themselves from online attacks. Internet traffic going through a corporate proxy can be modified by the proxy network in real time, causing certificate irregularities. Some other times, your organization offers their own CA certificate, which makes the situation even more complex.

You can try launching VSCode with --ignore-certificate-errors flag to disable strict certificate checking.

On Windows, the easiest way to do this is by running code.exe --ignore-certificate-errors from a Command Prompt window.

On Linux and macOS, you have to open Terminal app and run code --ignore-certificate-errors.

After that, try installing the extensions again to see whether the error message goes away.

Disable JS source maps

Source maps is basically a JavaScript engine feature that maps a combined/minified file back to an unbuilt state (think unminify). It was made for easier JavaScript debugging, but we don’t need to debug VSCode itself, so disabling it is safe. Plus, users have reported that disabling JavaScript source maps and CSS source maps solves XHR Failed error message .

In order to disable JavaScript source maps and CSS source maps in VSCode, fire up Command Palette and search for Developer: Toggle Shared Process.

image-20210531154850224

On Developer Tools that just pops up, click the Gear button (settings button) in the upper right corner.

image-20210531155130985

Uncheck Enable JavaScript source maps and Enable CSS source maps, then close the window.

image-20210531155245439

Change your DNS

If you live in a country where heavy internet censorship is implemented, such as China, Egypt or Turkey, maybe the firewall has blocked some Microsoft servers. You can try setting your DNS to Google DNS (8.8.8.8) or Cloudflare’s 1.1.1.1 servers to see if XHR Failed happens again or not. On Windows, you may have to run ipconfig /flushdns to flush the system’s DNS cache before changing the DNS.

Change-Windows-DNS-servers-to-Cloudflare-1.1.1.1

On Linux machines, you have to edit /etc/resolvconf/resolv.conf.d/base to make DNS changes persistent through restarts. Add these two lines to the file before rebooting so that the changes take effect.

nameserver 1.1.1.1
nameserver 1.0.0.1

Install the extension offline using VSIX file

All VSCode extensions is now available in the form of VSIX-packaged files. This allows for offline installation as well as extensions which are not originated from VSCode Marketplace.

You can download VSIX files directly from VSCode Marketplace or Open VSX Registry and install it offline, without the need for an internet connection. See our guide on How to install extensions in VSCode for detailed installation steps.

We hope that this article helps you solve the XHR Failed error in VSCode. VSCode is an awesome code editor, equipped with numerous features that supports developers. Here’s a few of them that we’ve covered, if you’re interested :

  • VSCode Format On Save – everything you need to know

  • Configure VSCode to work with Zsh

  • VSCode multiple cursors: advanced edition

  • Bind terminal commands to VSCode keyboard shortcuts

  • How to quickly create a comment block in VSCode

  • How to quickly duplicate a line in Visual Studio Code

  • How to comment out multiple lines in Visual Studio Code

  • How to automatically indent your code in Visual Studio Code

Понравилась статья? Поделить с друзьями:
  • Error x reader фанфики
  • Error x reader x ink
  • Error x reader smut
  • Error ошибка лишние данные после содержимого последнего столбца
  • Error ошибка инициализации графического устройства ок