Http запрос страницы javascript

Основы XMLHttpRequest

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/xmlhttprequest.

Объект XMLHttpRequest (или, как его кратко называют, «XHR») даёт возможность из JavaScript делать HTTP-запросы к серверу без перезагрузки страницы.

Несмотря на слово «XML» в названии, XMLHttpRequest может работать с любыми данными, а не только с XML.

Использовать его очень просто.

Пример использования

Как правило, XMLHttpRequest используют для загрузки данных.

Для начала посмотрим на пример использования, который загружает файл phones.json из текущей директории и выдаёт его содержимое:

// 1. Создаём новый объект XMLHttpRequest var xhr = new XMLHttpRequest(); // 2. Конфигурируем его: GET-запрос на URL 'phones.json' xhr.open('GET', 'phones.json', false); // 3. Отсылаем запрос xhr.send(); // 4. Если код ответа сервера не 200, то это ошибка if (xhr.status != 200) < // обработать ошибку alert( xhr.status + ': ' + xhr.statusText ); // пример вывода: 404: Not Found >else < // вывести результат alert( xhr.responseText ); // responseText -- текст ответа. >
var http = require('http'); var url = require('url'); var querystring = require('querystring'); var static = require('node-static'); var file = new static.Server('.', < cache: 0 >); function accept(req, res) < if (req.url == '/phones.json') < // искусственная задержка для наглядности setTimeout(function() < file.serve(req, res); >, 2000); > else < file.serve(req, res); >> // ------ запустить сервер ------- if (!module.parent) < http.createServer(accept).listen(8080); >else
       

Далее мы более подробно разберём основные методы и свойства объекта XMLHttpRequest , в том числе те, которые были использованы в этом коде.

Читайте также:  Получить первое значение словаря python

Настроить: open

xhr.open(method, URL, async, user, password)

Этот метод – как правило, вызывается первым после создания объекта XMLHttpRequest .

Задаёт основные параметры запроса:

  • method – HTTP-метод. Как правило, используется GET либо POST, хотя доступны и более экзотические, вроде TRACE/DELETE/PUT и т.п.
  • URL – адрес запроса. Можно использовать не только http/https, но и другие протоколы, например ftp:// и file:// . При этом есть ограничения безопасности, называемые «Same Origin Policy»: запрос со страницы можно отправлять только на тот же протокол://домен:порт , с которого она пришла. В следующих главах мы рассмотрим, как их можно обойти.
  • async – если установлено в false , то запрос производится синхронно, если true – асинхронно.

«Синхронный запрос» означает, что после вызова xhr.send() и до ответа сервера главный поток будет «заморожен»: посетитель не сможет взаимодействовать со страницей – прокручивать, нажимать на кнопки и т.п. После получения ответа выполнение продолжится со следующей строки.

«Асинхронный запрос» означает, что браузер отправит запрос, а далее результат нужно будет получить через обработчики событий, которые мы рассмотрим далее.

Заметим, что вызов open , в противоположность своему названию ( open – англ. «открыть») не открывает соединение. Он лишь настраивает запрос, а коммуникация инициируется методом send .

Отослать данные: send

Именно этот метод открывает соединение и отправляет запрос на сервер.

В body находится тело запроса. Не у всякого запроса есть тело, например у GET-запросов тела нет, а у POST – основные данные как раз передаются через body .

Отмена: abort

Вызов xhr.abort() прерывает выполнение запроса.

Ответ: status, statusText, responseText

Основные свойства, содержащие ответ сервера:

status HTTP-код ответа: 200 , 404 , 403 и так далее. Может быть также равен 0 , если сервер не ответил или при запросе на другой домен. statusText Текстовое описание статуса от сервера: OK , Not Found , Forbidden и так далее. responseText Текст ответа сервера.

Есть и ещё одно свойство, которое используется гораздо реже:

Если сервер вернул XML, снабдив его правильным заголовком Content-type: text/xml , то браузер создаст из него XML-документ. По нему можно будет делать запросы xhr.responseXml.querySelector(«. «) и другие.

Оно используется редко, так как обычно используют не XML, а JSON. То есть, сервер возвращает JSON в виде текста, который браузер превращает в объект вызовом JSON.parse(xhr.responseText) .

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

Если в методе open установить параметр async равным false , то запрос будет синхронным.

Синхронные вызовы используются чрезвычайно редко, так как блокируют взаимодействие со страницей до окончания загрузки. Посетитель не может даже прокручивать её. Никакой JavaScript не может быть выполнен, пока синхронный вызов не завершён – в общем, в точности те же ограничения как alert .

// Синхронный запрос xhr.open('GET', 'phones.json', false); // Отсылаем его xhr.send(); // . весь JavaScript "подвиснет", пока запрос не завершится

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

Из-за такой блокировки получается, что нельзя отослать два запроса одновременно. Кроме того, забегая вперёд, заметим, что ряд продвинутых возможностей, таких как возможность делать запросы на другой домен и указывать таймаут, в синхронном режиме не работают.

Из всего вышесказанного уже должно быть понятно, что синхронные запросы используются чрезвычайно редко, а асинхронные – почти всегда.

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

var xhr = new XMLHttpRequest(); xhr.open('GET', 'phones.json', true); xhr.send(); // (1) xhr.onreadystatechange = function() < // (3) if (xhr.readyState != 4) return; button.innerHTML = 'Готово!'; if (xhr.status != 200) < alert(xhr.status + ': ' + xhr.statusText); >else < alert(xhr.responseText); >> button.innerHTML = 'Загружаю. '; // (2) button.disabled = true;

Если в open указан третий аргумент true (или если третьего аргумента нет), то запрос выполняется асинхронно. Это означает, что после вызова xhr.send() в строке (1) код не «зависает», а преспокойно продолжает выполняться, выполняется строка (2) , а результат приходит через событие (3) , мы изучим его чуть позже.

Источник

JavaScript Get Request – How to Make an HTTP Request in JS

Joel Olawanle

Joel Olawanle

JavaScript Get Request – How to Make an HTTP Request in JS

When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.

This interaction between your frontend application and the backend server is possible through HTTP requests.

There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.

This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.

For this guide, we’ll retrieve posts from the free JSON Placeholder posts API.

There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.

How to Make a GET Request with the Fetch API

The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.

Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.

Let’s create a GET request to get a post from the JSON Placeholder posts API.

fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => console.log(json)); 

This will return a single post which you can now store in a variable and use within your project.

Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.

How to Make a GET Request with Axios

Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.

Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.

To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:

And now you can install Axios to your project by running the following command:

Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.

axios.get("https://jsonplaceholder.typicode.com/posts/1") .then((response) => console.log(response.data)) .catch((error) => console.log(error)); 

Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.

At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.

How to Make a GET Request with XMLHttpRequest

You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.

Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.

Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you’ll send the request, and finally listen to the server’s response.

const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1"); xhr.send(); xhr.responseType = "json"; xhr.onload = () => < if (xhr.readyState == 4 && xhr.status == 200) < console.log(xhr.response); >else < console.log(`Error: $`); > >; 

In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr . You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.

Another method you will use is .send() , which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.

If the client’s state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.

How to Make a GET Request with jQuery

Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:

With jQuery, you can access the GET method $.get() , which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => < console.log(data); >); 

Note: In the callback function, you have access to the request’s data and the request’s status.

You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:

Wrapping Up

In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?

If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.

Источник

Оцените статью