HTTP requests
An HTTP request asks a server for something. The two most common types are:
- GET gets data from a server, like asking for a page.
- POST sends data to a server, for example to create or update a record.
Method 1: Fetch API
fetch is built into modern browsers and Node.js 18 and later.
GET request:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
POST request:
const data = {
name: 'John Doe',
email: 'john@example.com'
};
fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));
With async/await it reads more clearly:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('HTTP ' + response.status);
console.log(await response.json());
} catch (error) {
console.error(error);
}
}
Note:
fetch does not fail on a 404 or 500 reply. Check response.ok yourself.Method 2: XMLHttpRequest
The older built-in way:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function () {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
} else {
console.error(xhr.statusText);
}
};
xhr.onerror = function () {
console.error('Network error');
};
xhr.send();
Method 3: jQuery Ajax
If your page already uses jQuery:
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.error(error);
}
});
Method 4: Axios
Axios is a popular library. Install it with npm install axios.
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
axios.post('https://api.example.com/users', { name: 'John Doe' })
.then(response => console.log(response.data));
Axios parses JSON for you and rejects the promise on error status codes.
Which one to use
| Method | Use it when |
|---|---|
| Fetch | You want the built-in modern option |
| XMLHttpRequest | You must support very old code |
| jQuery Ajax | The site already uses jQuery |
| Axios | You want extras like interceptors and automatic JSON |
Tips
- Browsers block requests to other domains unless the server allows them with CORS headers.
- Never put secret API keys in browser code.
- Handle errors and show a message to the user.
Quick recap
- Use
fetchfor new code. - Send JSON with
Content-Type: application/jsonandJSON.stringify.