change lan ip then save && apply
after timeout to 0s
no force apply windows pop up
and cannot save config
Waiting for configuration to get applied… 0s
tested on latest HEAD code and really unusable
Copy link
Contributor
Author
@jow-
it seems to be something related to your recently commits (don’t know which one)
Copy link
Contributor
Author
commit 843031f8197aa2c86585360c0f6d8a3b1ee02dee
Author: Jo-Philipp Wich <jo@mein.io>
Date: Sun Jan 6 17:08:37 2019 +0100
luci-base: luci.js: add HTTP request functions
Add a fetch() inspired HTTP request utility class to luci.js and
replace the old xhr.js class with a stub using the new request api.
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
This related?
Check the browser debug console for errors.
Copy link
Contributor
Author
console log
luci.js?v=git-19.200.40594-b76e583:58 Uncaught (in promise) Error: XHR request aborted by browser
at Object.handleReadyStateChange (luci.js?v=git-19.200.40594-b76e583:58)
Copy link
Contributor
Author
at this line
catch(e){rejectFn.call(opt,e);}});},handleReadyStateChange:function(resolveFn,rejectFn,ev){var xhr=this.xhr;if(xhr.readyState!==4)
return;if(xhr.status===0&&xhr.statusText===''){rejectFn.call(this,new Error('XHR request aborted by browser'));}
Copy link
Contributor
Author
somethings
luci.js?v=git-19.203.58942-a0254cb:57 GET http://192.168.56.254/ubus/?1563900586454 400 (Bad Request)
Copy link
Contributor
Author
I don’t really understand the javascript…
Copy link
Contributor
Author
handleReadyStateChange: function(resolveFn, rejectFn, ev) {
var xhr = this.xhr;
if (xhr.readyState !== 4)
return;
if (xhr.status === 0 && xhr.statusText === '') {
rejectFn.call(this, new Error('XHR request aborted by browser'));
}
else {
var response = new Response(
xhr, xhr.responseURL || this.url, Date.now() - this.start);
Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
.then(resolveFn.bind(this, response))
.catch(rejectFn.bind(this));
}
},
@jow-
hi could you help to resolve this?
it rase Error on rejectFn.call(this, new Error('XHR request aborted by browser'));
I don’t know what it is..
Copy link
Contributor
Author
@jow-
you could reproduce this error by changing lan ip from 192.168.0.1
to 192.168.100.1
when you connect to lan from PC
I can reproduce this behaviour while changing the lan ip address. It happens 10 seconds after the timeout started — reproducible with latest firefox and chrome on debian 10.
Please try this change:
diff --git a/modules/luci-base/htdocs/luci-static/resources/ui.js b/modules/luci-base/htdocs/luci-static/resources/ui.js index 1a98dbcc9..43afc698f 100644 --- a/modules/luci-base/htdocs/luci-static/resources/ui.js +++ b/modules/luci-base/htdocs/luci-static/resources/ui.js @@ -1929,7 +1929,7 @@ return L.Class.extend({ method: 'post', timeout: L.env.apply_timeout * 1000, query: L.ui.changes.confirm_auth - }).then(call); + }).then(call, call); }, delay); };
The proposed change fixes the problem for me — thank you!
Содержание
- How to make HTTP requests using XMLHttpRequest (XHR)
- Basic XHR Request
- xhr.open() Method
- xhr.send() Method
- XHR Events
- Request Timeout
- Response Type
- Request States ( xhr.readyState )
- Aborting Request
- Synchronous Requests
- HTTP Headers
- XHR POST Request
- XHR POST Request with with application/x-www-form-urlencoded
- XHR POST Request with JSON Data
- Cross-Origin Requests & Cookies
- XHR vs. jQuery
- XHR vs. Fetch API
- Handling Ajax errors with jQuery.
- JQuery 3.0: The error, success and complete callbacks are deprecated.
- One thought on “ Handling Ajax errors with jQuery. ”
- jQuery ajax readystate 0 состояние responsetext 0 ошибка statustext
- 5 ответов
- XMLHttpRequest
- The basics
- Response Type
- Ready states
- Aborting request
- Synchronous requests
- HTTP-headers
- POST, FormData
- Upload progress
- Cross-origin requests
- Summary
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.
Источник
Handling Ajax errors with jQuery.
This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.
Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
If you look at the code above, you will notice that I have two functions:
- success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
- error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.
The Ajax error function has three parameters:
In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
- status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
- statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.
JQuery 3.0: The error, success and complete callbacks are deprecated.
Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.
An example of done and fail being used:
Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.
Hopefully, you found this tutorial to be useful.
One thought on “ Handling Ajax errors with jQuery. ”
thanks its helpful 🙂 many of us not aware of error block in ajax
Источник
jQuery ajax readystate 0 состояние responsetext 0 ошибка statustext
Я получаю следующую ошибку: jquery ajax readystate 0 responsetext status 0 statustext error когда он: url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm) , однако он работает нормально, когда я даю его url(localhost:»»/embparse_page) на моем localhost.
Я попытался использовать заголовки, которые я нашел в поиске Google, и я использовал beforeSend:»» тоже, но это все еще не работает.
Я думаю, что главная проблема: XMLHttpRequest cannot load http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm. Origin «local server» is not allowed by Access-Control-Allow-Origin. но я этого не понимаю.
может кто-нибудь объяснить мне проблему, так как я совершенно новичок в этом.
5 ответов
Я получал эту ошибку, и в моем случае это не было связано с той же политикой происхождения. Я получил некоторую помощь от этой ссылке
мой случай был, у меня была кнопка ссылки, и я не использовал e.PreventDefault ()
ASPX
в JavaScript
та же политика происхождения. браузер не позволяет, когда вы находитесь на
для подключения к:
это так site1 не может украсть контент из site2 и притвориться, что это содержимое site1. Способы обойти это JSONP (Google maps используют, что я думаю) и имеющие site2 предоставить заголовки cors, но cors не поддерживаются в jQuery 1.* (может быть, не в 2.* либо), потому что IE имеет некоторые проблемы с его реализацией. В обеих ситуациях вам нужно site2 сотрудничать с вашим сайт, чтобы ваш сайт мог отображать его содержимое.
Если вы используете только это самостоятельно, то вы можете использовать Firefox и установить плагин forcecors. Для активации вы можете выбрать view => toolbars => add on bar и нажать на текст «cors» в правой нижней части экрана.
Я получал эту ошибку от моего вызова Ajax, и то, что исправило ее для меня, просто вставило «return false».
у меня была такая же проблема с Nginx (на стороне сервера ) и AngularJs (на стороне пользователя )
как сказал другой разработчик свою проблему Cors, здесь я просто хочу сказать, как я решаю свою проблему, может быть, кто-то использует этот подход 😉
сначала я добавил ниже строки в мои конфигурационные файлы Nginx (в linux — > /etc/nginx/sites-available / your domain) :
и с angularJs я отправляю свой запрос следующим образом:
я тестировал чтение на json/xml data и получил ошибку. значения содержания: Status[0] & readyState[0] и StatusText[error]; это успешно работает в Internet explorer, но не в Chrome, потому что домен должен быть таким же
это то, что исправлено
перейти к C:WINDOWSsystem32driversetchosts
поместите имя против вашего приложения localhost:
Источник
XMLHttpRequest
XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript.
Despite having the word “XML” in its name, it can operate on any data, not only in XML format. We can upload/download files, track progress and much more.
Right now, there’s another, more modern method fetch , that somewhat deprecates XMLHttpRequest .
In modern web-development XMLHttpRequest is used for three reasons:
- Historical reasons: we need to support existing scripts with XMLHttpRequest .
- We need to support old browsers, and don’t want polyfills (e.g. to keep scripts tiny).
- We need something that fetch can’t do yet, e.g. to track upload progress.
Does that sound familiar? If yes, then all right, go on with XMLHttpRequest . Otherwise, please head on to Fetch.
The basics
XMLHttpRequest has two modes of operation: synchronous and asynchronous.
Let’s see the asynchronous first, as it’s used in the majority of cases.
To do the request, we need 3 steps:
The constructor has no arguments.
Initialize it, usually right after new XMLHttpRequest :
This method specifies the main parameters of the request:
- method – HTTP-method. Usually «GET» or «POST» .
- URL – the URL to request, a string, can be URL object.
- async – if explicitly set to false , then the request is synchronous, we’ll cover that a bit later.
- user , password – login and password for basic HTTP auth (if required).
Please note that open call, contrary to its name, does not open the connection. It only configures the request, but the network activity only starts with the call of send .
This method opens the connection and sends the request to server. The optional body parameter contains the request body.
Some request methods like GET do not have a body. And some of them like POST use body to send the data to the server. We’ll see examples of that later.
Listen to xhr events for response.
These three events are the most widely used:
- load – when the request is complete (even if HTTP status is like 400 or 500), and the response is fully downloaded.
- error – when the request couldn’t be made, e.g. network down or invalid URL.
- progress – triggers periodically while the response is being downloaded, reports how much has been downloaded.
Here’s a full example. The code below loads the URL at /article/xmlhttprequest/example/load from the server and prints the progress:
Once the server has responded, we can receive the result in the following xhr properties:
status HTTP status code (a number): 200 , 404 , 403 and so on, can be 0 in case of a non-HTTP failure. statusText HTTP status message (a string): usually OK for 200 , Not Found for 404 , Forbidden for 403 and so on. response (old scripts may use responseText ) The server response body.
We can also specify a timeout using the corresponding property:
If the request does not succeed within the given time, it gets canceled and timeout event triggers.
To add parameters to URL, like ?name=value , and ensure the proper encoding, we can use URL object:
Response Type
We can use xhr.responseType property to set the response format:
- «» (default) – get as string,
- «text» – get as string,
- «arraybuffer» – get as ArrayBuffer (for binary data, see chapter ArrayBuffer, binary arrays),
- «blob» – get as Blob (for binary data, see chapter Blob),
- «document» – get as XML document (can use XPath and other XML methods) or HTML document (based on the MIME type of the received data),
- «json» – get as JSON (parsed automatically).
For example, let’s get the response as JSON:
In the old scripts you may also find xhr.responseText and even xhr.responseXML properties.
They exist for historical reasons, to get either a string or XML document. Nowadays, we should set the format in xhr.responseType and get xhr.response as demonstrated above.
Ready states
XMLHttpRequest changes between states as it progresses. The current state is accessible as xhr.readyState .
An XMLHttpRequest object travels them in the order 0 → 1 → 2 → 3 → … → 3 → 4 . State 3 repeats every time a data packet is received over the network.
We can track them using readystatechange event:
You can find readystatechange listeners in really old code, it’s there for historical reasons, as there was a time when there were no load and other events. Nowadays, load/error/progress handlers deprecate it.
Aborting request
We can terminate the request at any time. The call to xhr.abort() does that:
That triggers abort event, and xhr.status becomes 0 .
Synchronous requests
If in the open method the third parameter async is set to false , the request is made synchronously.
In other words, JavaScript execution pauses at send() and resumes when the response is received. Somewhat like alert or prompt commands.
Here’s the rewritten example, the 3rd parameter of open is false :
It might look good, but synchronous calls are used rarely, because they block in-page JavaScript till the loading is complete. In some browsers it becomes impossible to scroll. If a synchronous call takes too much time, the browser may suggest to close the “hanging” webpage.
Many advanced capabilities of XMLHttpRequest , like requesting from another domain or specifying a timeout, are unavailable for synchronous requests. Also, as you can see, no progress indication.
Because of all that, synchronous requests are used very sparingly, almost never. We won’t talk about them any more.
XMLHttpRequest allows both to send custom headers and read headers from the response.
There are 3 methods for HTTP-headers:
Sets the request header with the given name and value .
Several headers are managed exclusively by the browser, e.g. Referer and Host . The full list is in the specification.
XMLHttpRequest is not allowed to change them, for the sake of user safety and correctness of the request.
Another peculiarity of XMLHttpRequest is that one can’t undo setRequestHeader .
Once the header is set, it’s set. Additional calls add information to the header, don’t overwrite it.
Gets the response header with the given name (except Set-Cookie and Set-Cookie2 ).
Returns all response headers, except Set-Cookie and Set-Cookie2 .
Headers are returned as a single line, e.g.:
The line break between headers is always «rn» (doesn’t depend on OS), so we can easily split it into individual headers. The separator between the name and the value is always a colon followed by a space «: » . That’s fixed in the specification.
So, if we want to get an object with name/value pairs, we need to throw in a bit JS.
Like this (assuming that if two headers have the same name, then the latter one overwrites the former one):
POST, FormData
To make a POST request, we can use the built-in FormData object.
The form is sent with multipart/form-data encoding.
Or, if we like JSON more, then JSON.stringify and send as a string.
Just don’t forget to set the header Content-Type: application/json , many server-side frameworks automatically decode JSON with it:
The .send(body) method is pretty omnivore. It can send almost any body , including Blob and BufferSource objects.
Upload progress
The progress event triggers only on the downloading stage.
That is: if we POST something, XMLHttpRequest first uploads our data (the request body), then downloads the response.
If we’re uploading something big, then we’re surely more interested in tracking the upload progress. But xhr.onprogress doesn’t help here.
There’s another object, without methods, exclusively to track upload events: xhr.upload .
It generates events, similar to xhr , but xhr.upload triggers them solely on uploading:
- loadstart – upload started.
- progress – triggers periodically during the upload.
- abort – upload aborted.
- error – non-HTTP error.
- load – upload finished successfully.
- timeout – upload timed out (if timeout property is set).
- loadend – upload finished with either success or error.
Example of handlers:
Here’s a real-life example: file upload with progress indication:
Cross-origin requests
XMLHttpRequest can make cross-origin requests, using the same CORS policy as fetch.
Just like fetch , it doesn’t send cookies and HTTP-authorization to another origin by default. To enable them, set xhr.withCredentials to true :
See the chapter Fetch: Cross-Origin Requests for details about cross-origin headers.
Summary
Typical code of the GET-request with XMLHttpRequest :
There are actually more events, the modern specification lists them (in the lifecycle order):
- loadstart – the request has started.
- progress – a data packet of the response has arrived, the whole response body at the moment is in response .
- abort – the request was canceled by the call xhr.abort() .
- error – connection error has occurred, e.g. wrong domain name. Doesn’t happen for HTTP-errors like 404.
- load – the request has finished successfully.
- timeout – the request was canceled due to timeout (only happens if it was set).
- loadend – triggers after load , error , timeout or abort .
The error , abort , timeout , and load events are mutually exclusive. Only one of them may happen.
The most used events are load completion ( load ), load failure ( error ), or we can use a single loadend handler and check the properties of the request object xhr to see what happened.
We’ve already seen another event: readystatechange . Historically, it appeared long ago, before the specification settled. Nowadays, there’s no need to use it, we can replace it with newer events, but it can often be found in older scripts.
Источник
пока моя страница загружает контент через XHR, если пользователь нажимает кнопку «стоп» или щелкает, чтобы перейти на другую страницу, вызывается функция XHR error (). Обычно это не было бы большим делом, за исключением шока пользователя, увидев много (красных) сообщений об ошибках на странице.
сообщения действительны-действительно произошла ошибка при извлечении содержимого, но это связано с взаимодействием пользователя, а не из-за сбоя системы.
есть ли способ различать a (404 | 500 / timeout error) и ошибка, вызванная тем, что пользователь нажал кнопку остановки браузера ?
EDIT: я использую Dojo (следовательно, ссылку на функцию ошибки), но я считаю, что это будет ситуация, которая является общей для любой реализации XHR. Я буду смотреть в readyState объекта xhr, когда error () вызывается
1 ответов
чтобы различать ошибки HTTP (404
, 401
, 403
, 500
, etc..) и запросить ошибки аборта (т. е. пользователь нажал Esc или перешел на другую страницу) , вы можете проверить XHR.свойство status, если запрос был прерван, член status будет равен нулю:
document.getElementById('element').onclick = function () {
postRequest ('test/', null, function (response) { // success callback
alert('Response: ' + response);
}, function (xhr, status) { // error callback
switch(status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error ' + status);
}
});
};
простая функция postRequest:
function postRequest (url, params, success, error) {
var xhr = XMLHttpRequest ? new XMLHttpRequest() :
new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("POST", url, true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success(xhr.responseText);
} else {
error(xhr, xhr.status);
}
}
};
xhr.onerror = function () {
error(xhr, xhr.status);
};
xhr.send(params);
}
выполнить приведенный выше фрагмент здесь.
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.
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.
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.
On Developer Tools that just pops up, click the Gear button (settings button) in the upper right corner.
Uncheck Enable JavaScript source maps and Enable CSS source maps, then close the window.
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.
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
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 thexhr.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 beGET
,POST
,DELETE
,PUT
, etc.URL
— The URL to request, a string or a URL objectasnyc
— Specify whether the request should be made asynchronously or not. The default value istrue
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 thexhr.onreadystatechange
event withxhr.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 anXMLHttpRequest
instance after following all redirects. This is the only way to retrieve theLocation
header.
Response Type
We can use the xhr.responseType
property to set the expected response format:
- Empty (default) or
text
— plain text json
— parsed JSONblob
— binary data Blobdocument
— XML documentarraybuffer
—ArrayBuffer
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 stateOPENED
(1) — The request beginsHEADERS_RECEIVED
(2) — The HTTP headers receivedLOADING
(3) — Response is loadingDONE
(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.