As it looks, xhr poll error is triggered by io.socket.engineio.client.transports.PollingXHR.java.
Normally, PollingXHR is initialized on multiple threads within short time intervals. These «parallel» requests are then executed against the server.
Normally, these requests are returned (or fail) in order, and a disconnected socket is reconnected if at least one of these parallel requests returns 200 OK. As long as an error is returned, the socket stays disconnected.
If a race condition occurs, and the socket is reconnected, but then an earlier request returns an error, xhr poll error is returned and the successfully connected socket is disconnected.
around ln 220:
final int statusCode = xhr.getResponseCode();
if (HttpURLConnection.HTTP_OK == statusCode) {
self.onLoad();
} else {
self.onError(new IOException(Integer.toString(statusCode))); // [A]
}
} catch (IOException e) {
self.onError(e); // [B]
} catch (NullPointerException e) {
// It would occur to disconnect
// https://code.google.com/p/android/issues/detail?id=76592
self.onError(e);
} finally {
try {
if (output != null) output.close();
} catch (IOException e) {}
}
In case [A], we have the situation where the server responded with an error, in case [B] we have the situation, where (for whatever reason) the server couldn’t be reached and a timeout occurs.
To prevent this error, the receiver of the event would need to look into the reason for the IOException, and if it would determine a timeout has occurred [if it can do this as both are IOExceptions with just a description], instead of throwing «xhr poll error» and disconnecting the socket, it should first check if the socket is already connected, and in this case swallow and ignore the timeout of any parallel thread (because the socket is connected already).
[This here is a speculation and I am still investigating into this.]
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.onloadevent only works in modern browsers (IE10+, Firefox, Chrome, Safari). If you want to support old browsers, use thexhr.onreadystatechangeevent 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 istrueusername&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.onreadystatechangeevent 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.responseURLproperty returns the final URL of anXMLHttpRequestinstance after following all redirects. This is the only way to retrieve theLocationheader.
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—ArrayBufferfor 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.
Содержание
- 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.
Источник
The XMLHttpRequest method
send() sends the request to the server.
If the
request is asynchronous (which is the default), this method returns as soon as the
request is sent and the result is delivered using events. If the request is synchronous,
this method doesn’t return until the response has arrived.
send() accepts an optional parameter which lets you specify the request’s
body; this is primarily used for requests such as PUT. If the request
method is GET or HEAD, the body
parameter is ignored and the request body is set to null.
If no Accept header has been set using the
setRequestHeader(), an
Accept header with the type "*/*" (any type) is sent.
Syntax
Parameters
bodyOptional-
A body of data to be sent in the XHR request. This can be:
- A
Document, in which case it is serialized before being sent. - An
XMLHttpRequestBodyInit, which per the Fetch spec can be aBlob, anArrayBuffer, aTypedArray, aDataView, aFormData, aURLSearchParams, or a string literal or object. null
If no value is specified for the body, a default value of
nullis used. - A
The best way to send binary content (e.g. in file uploads) is by using
a TypedArray, a DataView or a Blob object
in conjunction with the send() method.
Return value
Exceptions
InvalidStateErrorDOMException-
Thrown if
send()has already been invoked for the request, and/or the request is complete. NetworkErrorDOMException-
Thrown if the resource type to be fetched is a Blob, and the method is not
GET.
Example: GET
const xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
xhr.onload = () => {
// Request finished. Do processing here.
};
xhr.send(null);
// xhr.send('string');
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);
Example: POST
const xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = () => { // Call a function when the state changes.
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
Specifications
| Specification |
|---|
| XMLHttpRequest Standard # the-send()-method |
Browser compatibility
BCD tables only load in the browser
See also
О том, как сделать запрос на сервер +2
JavaScript, Разработка веб-сайтов, Программирование
Рекомендация: подборка платных и бесплатных курсов 3D max — https://katalog-kursov.ru/
… и получить ответ, разумеется.
Доброго времени суток, друзья!
При разработке веб-приложений часто возникает необходимость получения данных с сервера.
На сегодняшний день в JavaScript существует большое количество способов это сделать.
В статье будут рассмотрены следующие приемы:
- XMLHttpRequest
- JQuery.ajax
- Qwest
- SuperAgent
- Http-client
- Axios
- Fetch
Рассмотрим синтаксис каждого способа на примере простых GET и POST-запросов, остановимся на их плюсах и минусах.
В завершение решим парочку задач с использованием XMLHttpRequest, Axios и Fetch.
Большая часть теории является переводом этой статьи.
Итак, поехали.
XMLHttpRequest
Объект XMLHttpRequest — это старейший метод из рассматриваемых. Разумеется, другие методы превосходят его по функциональности. Однако он продолжает работать (в чем мы убедимся, когда перейдем к примерам) и может быть полезен для обеспечения обратной совместимости со старыми браузерами.
GET
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://example.com/users')
xhr.send()
xhr.onload = function() {
if (xhr.status != 200) {
console.log(`error ${xhr.status}: ${xhr.statusText}`)
} else {
// работаем с данными
console.log(xhr.response)
}
}
xhr.onerror = function() {
// обрабатываем ошибки
}
POST
let formData = new FormData()
formData.append('name', 'Harry')
let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/users');
xhr.send(formData);
xhr.onload = () => console.log(xhr.response);
Преимущества:
- работает во всех браузерах
- является встроенным API браузера
- отсутствует необходимость загрузки из внешнего источника
- завершенность, стабильность
Недостатки:
- неуклюжий и многословный синтаксис
- может привести к «аду функций обратного вызова»
- заменяется на fetch при интерпретации
JQuery.ajax
Это широко используемая с давних пор библиотека для отправки асинхронных запросов.
Все методы ajax возвращают абстракцию (надстройку) над объектом XMLHttpRequest.
GET
$.ajax({
url: 'https://example.com/users'
}).done(function(data) {
// работаем с данными
console.log(data)
}).fail(function(error) {
// обрабатываем ошибки
console.log(error)
})
POST
$.ajax({
method: "POST",
url: "https://example.com/users",
data: { name: 'Harry', age: 29 }
})
.done(function(msg) {
console.log( 'data saved: ' + msg );
})
Преимущества:
- хорошая поддержка и документация
- объект запроса можно настраивать
- используется во многих проектах
- прост в изучении
- имеется возможность прерывания запроса
Недостатки:
- не является встроенным API браузера
- необходимо загружать из внешнего источника
- приходится добавлять весь функционал JQuery
Qwest
Qwest — это простая ajax-библиотека, основанная на промисах и поддерживающая тип данных XmlHttpRequest2, похожий на ArrayBuffer, Blob и FormData.
GET
qwest.get('https://example.com/users')
.then(function(xhr, response) {
// работаем с данными
console.log(response)
});
POST
qwest.post('https://example.com/users', {
name: 'Harry',
age: 29
})
.then(function(xhr, response) {
// работаем с данными
console.log(response)
})
.catch(function(e, xhr, response) {
// обрабатываем ошибки
console.log(e)
})
Преимущества:
- можно устанавливать ограничения на количество запросов
- основан на промисах
Недостатки:
- XmlHttpRequest2 доступен не во всех браузерах
- не является встроенным
- необходимо загружать из внешнего источника
Superagent
Superagent (visionmedia) — это простой в изучении ajax API, созданный для повышения гибкости и читаемости кода. Он также работает с node.js.
GET
const superagent = require('superagent')
superagent
.get('https://example.com/users')
.end((err, res) => {
// работаем с данными
console.log(res)
})
Метод query() принимает объекты — строки запросов.
superagent.get('https://example.com/users')
.query({
name: 'Harry'
})
.query({
age: 29
})
.end(response => {
console.log(response)
})
POST
superagent.post('https://example.com/users')
.send({
name: 'Harry'
})
.set('Accept', 'application/json')
.end(response => {
console.log(response)
})
Преимущества:
- основан на промисах
- работает как в браузере, так и в node.js
- для прерывания запроса вызывается метод request.abort()
- хорошо известная в сообществе разработчиков библиотека
- простой интерфейс
- поддержка повторных запросов
Недостатки:
- не поддерживается мониторинг процесса загрузки
- не является встроенным
- необходимо загружать из внешнего источника
Http-client
Http-client позволяет формировать клиент HTTP, используя Fetch API.
GET
// используем ES-6 модули
import {
createFetch,
base,
accept,
parse
} from 'http-client'
const fetch = createFetch(
base('https://example.com/users'),
accept('application.json'),
parse('json')
)
fetch('https://example.com/users').then(response => {
console.log(response.jsonData)
})
POST
import {
createFetch,
method,
params
} from 'http-client'
const fetch = createFetch(
params({
name: 'Harry'
}),
base('htpps://example.com/users')
)
Преимущества:
- работает как в браузере, так и в node.js
- используется сервис-воркерами
- основан на промисах
- обеспечивает хорошую защиту в политике общего происхождения
Недостатки:
- не является встроенным
- необходимо загружать из внешнего источника
Axios
Основанная на промисах библиотека для работы с запросами как в браузере, так и в node.js.
GET
const axios = require('axios');
axios.get('https://example.com/users')
.then(function(response) {
// работаем с данными
console.log(response);
})
.catch(function(error) {
// обрабатываем ошибки
console.log(error);
})
POST
axios.post('/user', {
name: 'Harry',
age: 29
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
})
Преимущества:
- использует промисы для решения проблемы «ада функций обратного вызова»
- работает как в браузере, так и в node.js
- поддерживается мониторинг процесса загрузки
- можно устанавливать задержку получения ответа
- имеется возможность настройки запросов
- реализована отмена промисов
- автоматическое преобразование данных в JSON
Недостатки:
- не является встроенным
- необходимо загружать из внешнего источника
Fetch
Fetch является встроенным API браузера, пришедшим на смену XMLHttpRequest. Он сильно упрощает работу с запросами. В основе fetch лежат промисы.
GET
fetch('https://example.com/users')
.then(response => response.json())
.then(result => console.log(result)))
POST
fetch('https://example.com/users', {
method: 'post',
headers: {
'Accept': 'application/json'
},
body: JSON.stringify({
name: 'Harry'
})
})
.then(res => res.json())
.then(res => console.log(res))
Преимущества:
- является встроенным
- не требуется загружать из внешнего источника
- основан на промисах
- не нуждается в определении зависимостей
- поддерживается всеми современными браузерами
- официальная замена XMLHttpRequest
- низкий порог вхождения
Недостатки:
- двухэтапный процесс: сначала мы делаем запрос, затем вызываем метод .json(). В Axios мы получаем ответ в формате JSON по умолчанию
- промис, возвращаемый Fetch(), отклоняется только в случае возникновения каких-либо проблем с сетью. Если ответом сервера будет 404 или 500, промис все равно выполняется
- не хватает полезного функционала других библиотек, например, возможности отменять запросы
- fetch по умолчанию не отправляет и не получает куки с сервера, что может привести к квалификации запроса как неаутентифицированного и его блокировке. Одним из способов решения данной проблемы является добавление { credentials: ‘same-origin’ } в объект запроса
Примеры
Давайте посмотрим, как XMLHttpRequest, Fetch и Axios используются на практике. В задачах будет использоваться JSONPlaceholder — фейковый онлайн REST API для тестирования и прототипирования (проще говоря, учебная база данных).
XMLHttpRequest
Задача: получить список пользователей и вывести этот список в консоль.
Решение:
// создаем объект XMLHttpRequest с помощью конструктора
let xhr = new XMLHttpRequest()
// открываем соединение
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')
// отправляем запрос
xhr.send()
/*xhr.onload = function() {
if (xhr.status != 200) {
console.log(`error ${xhr.status}:${xhr.statusText}`)
} else {
console.table(JSON.parse(xhr.response))
}
}*/
// сокращенный вариант
// если запрос провалился, выводим в консоль статус
// если выполнился, парсим ответ и выводим его в консоль
xhr.onload = () => xhr.status != 200 ? console.error(xhr.status) : console.table(JSON.parse(xhr.response))
// мониторим процесс загрузки
// если ответ содержит заголовок Content-Length, показываем процесс загрузки в байтах
// если не содержит, показываем общее количество загруженных байт
xhr.onprogress = event => {
if (event.lengthComputable) {
console.dir(`received ${event.loaded} of ${event.total} bytes`)
} else {
console.dir(`received ${event.loaded} bytes`)
}
}
// обрабатываем другие ошибки
xhr.onerror = () => console.error('error')
Результат:
Код на GitHub.
Fetch
Задача: аналогичная.
Решение (сравните с XMLHttpRequest):
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => console.table(json))
.catch(error => console.error(error))
Результат:
Код на GitHub.
Либо, если вам больше нравится async/await:
(async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
const data = await response.json()
console.table(data)
} catch (error) {
console.error(error)
} finally {
console.log('done')
}
})()
Результат:
Код на GitHub.
Немного усложним задачу: теперь нужно получить с сервера изображения и сформировать из них галерею.
Решение:
const url = 'https://jsonplaceholder.typicode.com/photos/'
getPhotosAndMakeGallery(url)
function getPhotosAndMakeGallery(url) {
for (let i = 1; i < 11; i++) {
fetch(url + i)
.then(response => response.json())
.then(photo => {
let img = document.createElement('img')
img.src = photo.url
document.body.append(img)
})
}
}
Результат:
Код на GitHub.
Axios
Для подключения данной библиотеки необходимо добавить <script src=«unpkg.com/axios/dist/axios.min.js»></script> в head документа.
Задача: получить список пользователей и вывести их в консоль.
Решение:
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => console.table(response.data))
.catch(error => console.log(error))
Код на GitHub.
Либо, если вы предпочитаете async/await:
(async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
console.table(response.data);
} catch (error) {
console.error(error);
}
})()
Код на GitHub.
Усложняем задачу: получить todos и сформировать список.
Решение:
const url = 'https://jsonplaceholder.typicode.com/todos/'
getTodosAndMakeList()
function getTodosAndMakeList() {
const ul = document.createElement('ul')
document.body.append(ul)
for (let i = 1; i < 21; i++) {
axios.get(url + i)
.then(response => {
let li = document.createElement('li')
li.textContent = `title: ${response.data.title}; completed: ${response.data.completed}`
ul.append(li)
})
.catch(error => console.log(error))
}
}
Результат:
Код на GitHub.
Еще усложняем: получить пользователей, комментарии и фото, объединить эти данные и представить все в удобочитаемом виде.
Решение:
function getUsers(i) {
return axios.get('https://jsonplaceholder.typicode.com/users/' + i)
}
function getComments(i) {
return axios.get('https://jsonplaceholder.typicode.com/comments/' + i)
}
function getPhotos(i) {
return axios.get('https://jsonplaceholder.typicode.com/photos/' + i)
}
(async() => {
for (let i = 1; i < 7; i++) {
let request = await axios.all([getUsers(i), getComments(i), getPhotos(i)])
.then(axios.spread(function(user, comment, photo) {
let figure = document.createElement('figure')
document.body.append(figure)
let figcaption = document.createElement('figcaption')
figcaption.textContent = `Post ${i}`
figure.append(figcaption)
let img = document.createElement('img')
img.src = photo.data.url
figure.append(img)
let userName = document.createElement('p')
userName.innerHTML = `<span>Name:</span> ${user.data.username}`
figure.append(userName)
let userComment = document.createElement('p')
userComment.innerHTML = `<span>Comment:</span> ${comment.data.body}`
figure.append(userComment)
}))
}
})()
Результат:
Код на GitHub.
Благодарю за внимание.
Счастливого кодинга!







