This article comprehensively explains 6 mainstream interface request solutions, covering native APIs and popular library implementations, and provides directly reusable code templates and best practice guides.
1. XMLHttpRequest (native solution)
1.1 Basic use
const xhr = new XMLHttpRequest(); ('GET', '/data', true); = function() { if ( >= 200 && < 300) { (()); } else { ('Request failed:', ); } }; = function() { ('Network Error'); }; ();
1.2 Advanced Configuration
// POST request example('POST', '/submit'); ('Content-Type', 'application/json'); (({ name: 'John', age: 25 })); // Timeout control = 5000; = function() { ('Request timed out'); };
advantage:
- Browser native support
- Fine control of the request process
shortcoming:
- Callback hell problem
- Response analysis needs to be processed manually
- Lack of Promise support
2. Fetch API (modern standard)
2.1 Basic Request
fetch('/data') .then(response => { if (!) { throw new Error(`HTTP error! status: ${}`); } return (); }) .then(data => (data)) .catch(error => ('Request failed:', error));
2.2 Advanced Configuration
// POST request configurationfetch('/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token' }, body: ({ title: 'New Post' }), credentials: 'include', // Carry cookies mode: 'cors' // Cross-domain mode}); // Cancel requestconst controller = new AbortController(); setTimeout(() => (), 5000); fetch(url, { signal: }) .catch(err => { if ( === 'AbortError') { ('Request was cancelled'); } });
Advantages:
- Promise chain call
- Built-in response parsing method
- Support streaming data processing
Limited:
- No cookies are carried by default
- Error handling requires additional judgment
- Direct configuration does not support timeout
3. Axios (popular library)
3.1 Basic usage
import axios from 'axios'; // GET request('/user?ID=12345') .then(response => ()) .catch(error => (error)); // POST request('/user', { firstName: 'Fred', lastName: 'Flintstone' }, { headers: { 'X-Custom-Header': 'value' } });
3.2 Global configuration
// Create an instanceconst api = ({ baseURL: '', timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest' } }); // Request for interception(config => { = `Bearer ${('token')}`; return config; }); // Response to intercept( response => , error => { if (?.status === 401) { = '/login'; } return (error); } );
Core features:
- Automatically convert JSON data
- Client XSRF Protection
- Concurrent request processing
- Request cancel support
4. jQuery Ajax (traditional solution)
4.1 Basic implementation
$.ajax({ url: '/data', method: 'GET', dataType: 'json', success: function(data) { (data); }, error: function(xhr, status, error) { (error); } });
4.2 Global configuration
// Set default parameters$.ajaxSetup({ timeout: 3000, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); // Use Promise$.getJSON('/items') .done(data => (data)) .fail((jqXHR, textStatus, errorThrown) => { (textStatus, errorThrown); });
Applicable scenarios:
- Old project maintenance
- Need to be compatible with old browsers such as IE9
5. WebSocket (real-time communication)
5.1 Basic implementation
const socket = new WebSocket('wss:///ws'); = function() { ('Connection established'); (({ action: 'subscribe', channel: 'updates' })); }; = function(event) { const data = (); ('Received the message:', data); }; = function(event) { ('Connection closed:', , ); };
5.2 Disconnection of wires
let socket; function connect() { socket = new WebSocket(url); = function() { setTimeout(connect, 5000); }; } connect();
Best Practices:
- Keep the connection with heartbeat package
- Implement message queue retransmission mechanism
- Encapsulation using protocols such as STOMP
6. GraphQL request
6.1 Implementation using Fetch
fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ query: ` query GetUser($id: ID!) { user(id: $id) { name email } } `, variables: { id: '123' } }) }) .then(res => ()) .then(data => ());
6.2 Using the Apollo Client
import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; const client = new ApolloClient({ uri: '/graphql', cache: new InMemoryCache() }); ({ query: gql` query GetBooks { books { title author } } ` }).then(result => ());
7. Comprehensive comparison and selection guide
plan | Applicable scenarios | advantage | shortcoming |
---|---|---|---|
XMLHttpRequest | Older projects that require fine control | No additional dependencies required | The code is verbose, callback hell |
Fetch API | Modern browser project | Native support, concise syntax | Errors and timeouts need to be handled manually |
Axios | Complex enterprise-level applications | Comprehensive functions, interceptor mechanism | Increase package volume |
jQuery Ajax | Maintain old jQuery projects | Simplify asynchronous operations | Depend on jQuery, outdated |
WebSocket | Real-time communication requirements | Two-way real-time communication | High complexity |
GraphQL | Complex data query scenarios | Accurate data acquisition and reduce the number of requests | Steep learning curve |
8. Best practices and safety protection
8.1 General Security Policy
// CSRF protection = 'csrftoken'; = 'X-CSRFToken'; // Request a signaturefunction signRequest(config) { const timestamp = (); const signature = ('sha256', SECRET) .update(`${}${timestamp}`) .digest('hex'); ['X-Signature'] = signature; ['X-Timestamp'] = timestamp; return config; }
8.2 Performance optimization solution
// Request cacheconst cache = new Map(); async function cachedFetch(url) { if ((url)) { return (url); } const response = await fetch(url); const data = await (); (url, data); return data; } // Request mergelet pendingRequests = {}; function batchRequest(url) { if (!pendingRequests[url]) { pendingRequests[url] = fetch(url).then(res => ()); } return pendingRequests[url]; }
9. Standard paradigm for error handling
9.1 Unified Error Handling
// Axios Error Classificationfunction handleError(error) { if () { // Server response exception (status code outside 2xx) ('Server Error:', ); } else if () { // The request has been issued but no response ('Network Error:', ); } else { // Error in request configuration ('Config Error:', ); } }
9.2 Retry mechanism implementation
function fetchWithRetry(url, retries = 3) { return new Promise((resolve, reject) => { const attempt = (remaining) => { fetch(url) .then(resolve) .catch(error => { if (remaining > 0) { (`Remaining retry times: ${remaining}`); attempt(remaining - 1); } else { reject(error); } }); }; attempt(retries); }); }
10. TypeScript type enhancement
10.1 Axios response type
interface ApiResponse<T> { code: number; data: T; message: string; } const api = ({ baseURL: '/api', responseType: 'json' }); ( (response): ApiResponse<unknown> => { if ( !== 200) { throw new Error(); } return ; } ); // Use generic requestfunction getUser<T>(id: string) { return <ApiResponse<T>>(`/users/${id}`); }
Summary and expansion direction
Extended learning suggestions:
- Master HTTP/2 server push technology
- Research the new WebTransport protocol
- Learn Service Worker Offline Caching
- Explore WebRTC peer-to-peer communication
Version compatibility solution:
// Dynamic loading of polyfillif (!) { import('whatwg-fetch').then(() => { ('Fetch polyfill loaded'); }); }
Flexible selection of request solutions based on project requirements, modern projects recommend priority to using Fetch API or Axios. Always follow safety best practices and find a balance between performance and functional requirements.
This is the article about 6 mainstream interface request technologies in front-end JavaScript. For more related JS interface request content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!