Junior
What tools do you use to interact with the server?
sobes.tech AI
Answer from AI
-
XMLHttpRequest (XHR):
const xhr = new XMLHttpRequest(); xhr.open('GET', '/api/data', true); // Setting up the request xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 400) { const data = JSON.parse(xhr.responseText); // Handling successful response console.log(data); } else { // Handling errors console.error('Request error:', xhr.status); } }; xhr.onerror = function() { // Handling network errors console.error('Network error'); }; xhr.send(); // Sending the request -
Fetch API:
fetch('/api/data') .then(response => { if (!response.ok) { throw new Error('HTTP status ' + response.status); // Handling HTTP errors } return response.json(); // Parsing JSON }) .then(data => { console.log(data); // Handling data }) .catch(error => { console.error('Request error:', error); // Handling other errors }); -
Libraries based on Fetch or XHR:
- Axios:
// Installing Axios: npm install axios import axios from 'axios'; axios.get('/api/data') .then(response => { console.log(response.data); // Accessing data via .data }) .catch(error => { console.error('Request error:', error); // Handling errors }); - jQuery.ajax: (If jQuery is used)
// jQuery library required $.ajax({ url: '/api/data', method: 'GET', dataType: 'json', // Expected data type success: function(data) { console.log(data); // Handling successful response }, error: function(jqXHR, textStatus, errorThrown) { console.error('Request error:', textStatus, errorThrown); // Handling errors } });
- Axios:
-
WebSockets: For real-time bidirectional communication.
const socket = new WebSocket('ws://localhost:8080'); // Connecting to WebSocket server socket.onopen = function(event) { console.log('WebSocket connected'); // Connection event socket.send('Hello from client!'); // Sending a message }; socket.onmessage = function(event) { console.log('Message from server:', event.data); // Receiving a message }; socket.onerror = function(event) { console.error('WebSocket error:', event); // Error event }; socket.onclose = function(event) { if (event.wasClean) { console.log('Connection closed cleanly, code=' + event.code + ' reason=' + event.reason); } else { console.error('Connection interrupted'); // For example, server process killed } }; // Closing the connection // socket.close();
The choice of tool depends on project requirements, the need to work with promises, ease of request handling, and additional features (interceptors, request cancellation with Axios, etc.). Fetch API is the modern standard for asynchronous requests, while Axios is a powerful library offering additional capabilities. XHR is less used in new projects but important for understanding basics. WebSockets are indispensable for interactive applications with real-time data exchange.