Introduction
When developers need to retrieve or send data to a server, calling a REST API from JavaScript is one of the most common tasks. Whether you’re building a simple web page that displays weather data, integrating with a payment service, or syncing a mobile app with a backend, JavaScript provides several built‑in mechanisms to issue HTTP requests. Understanding the core concepts—like XMLHttpRequest, fetch, and async/await—helps you choose the right approach for different scenarios, keep your code maintainable, pornofilm, and avoid common pitfalls such as unhandled rejections or CORS issues.
Steps
1. Choose the Right Method
| Method | When to Use | Advantages | Limitations |
|---|---|---|---|
| XMLHttpRequest | Legacy browsers, simple GET/POST requests | Fully supported in all environments | Verbose, no built‑in promise wrapper |
| fetch | Modern browsers, cleaner syntax, promise‑based | Concise API, automatic JSON parsing | Polyfill needed for older browsers |
| axios | Complex projects, interceptors, auto‑error handling | dependable feature set, request/response interceptors | Adds extra library overhead |
| superfetch (or other custom wrappers) | Large‑scale apps, TypeScript support | Type safety, reusable utilities | Additional learning curve |
2. Set Up the Request Object
Using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status);
}
};
xhr.onerror = function() {
console.log('Network error occurred');
};
xhr.send();
Key points:
openconfigures the HTTP method and URL.
On top of that, -onloadfires when the request completes;statuscodes are numeric (200 = success). -sendinitiates the request; for POST you can pass a body string.
Using fetch
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // automatically parses JSON
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Fetch error:', error);
});
- fetch returns a promise that resolves to the Response object.
response.okis a boolean shortcut for status codes 200‑299.response.json()parses the body as JSON; other methods liketext()orblob()are also available.
Using async/await (ES2017+)
async function getApiData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Data:', data);
return data;
} catch (error) {
console.error('Async error:', error);
throw error; // rethrow if caller wants to handle it
}
}
getApiData('https://api.example.com/data');
asyncmarks the function as returning a promise;awaitpauses execution until the promise resolves.- This pattern reads like synchronous code, improving readability for sequential API calls.
3. Handle Different HTTP Methods
| Method | fetch Example | XMLHttpRequest Example |
|---|---|---|
| GET | fetch('url') |
xhr.open('GET', 'url') |
| POST | fetch('url', { method: 'POST', headers: {...}, body: JSON.stringify(data) }) |
xhr.open('POST', 'url'); xhr.send(JSON.So stringify(data)); |
| PUT / DELETE | Similar to POST with method: 'PUT' or method: 'DELETE' |
xhr. open('PUT', 'url'); etc. |
When sending data:
const payload = { name: 'Alice', age: 30 };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
},
body: JSON.stringify(payload)
};
fetch('https://api.example.com/users', options)
.then(r => r.json())
.then(console.log);
4. Manage Headers and Authentication
- Content-Type: tells the server the format of the body (JSON, form‑data, etc.).
- Authorization: often used with Bearer tokens or Basic auth.
- Accept: can specify desired response format (e.g.,
application/vnd.api+json).
Example with custom headers:
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('X-Custom-Header', 'my-value');
fetch('https://api.example.com/endpoint', { method: 'POST', headers, body: '{}' });
5. Deal with CORS (Cross‑Origin Resource Sharing)
If the API resides on a different domain than your script, browsers enforce CORS policies. Most servers respond with an Access-Control-Allow-Origin header. If you encounter errors:
- Verify the server includes the appropriate CORS headers.
- For development, tools like CORS proxy can be used, but they are not suitable for production.
- Ensure credentials (cookies, HTTP auth) are handled correctly: set
credentials: 'include'if needed.
6. Error Handling and Status Codes
| Status | Meaning | Typical Action |
|---|---|---|
| 200‑299 | Success | Process response data. Even so, |
| 400 | Bad Request | Log client‑side validation errors. Now, |
| 401 | Unauthorized | Prompt user to log in or refresh token. |
| 403 | Forbidden | Check permissions. On the flip side, |
| 404 | Not Found | Handle gracefully (show “resource missing”). |
| 500‑599 | Server Error | Retry logic or display generic error message. |
Always inspect response.status and response.ok before assuming success Most people skip this — try not to. Simple as that..
7. Optimize Performance
- Debounce rapid successive requests (e.g., search-as-you-type).
- Cache responses using
localStorageor a dedicated cache library. - Use HTTP/2 multiplexing to reduce latency for multiple concurrent calls.
- For large payloads, consider streaming or pagination to avoid blocking the UI.
Scientific Explanation
At a lower level, calling a REST API from JavaScript involves the browser’s networking stack and the HTTP protocol. Here's the thing — when you invoke fetch or XMLHttpRequest, the browser creates a TCP socket to the target host, performs a DNS lookup, and sends an HTTP request line (method, path, version) followed by headers. The server processes the request, generates a response, and closes the connection (or keeps it alive for HTTP keep‑alive) It's one of those things that adds up..
The promise mechanism in modern