Overview
Sending HTTP requests from the browser console is an essential skill for frontend developers, useful for testing APIs and debugging interfaces.
Using the Fetch API (Recommended)
GET Request
// Simple GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Async await approach
(async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
})();
POST Request
// POST JSON data
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John',
email: '[email protected]'
})
})
.then(response => response.json())
.then(data => console.log(data));
// POST Form data
const formData = new FormData();
formData.append('username', 'john');
formData.append('email', '[email protected]');
fetch('https://api.example.com/users', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data));
Authenticated Requests
// Using Bearer Token
fetch('https://api.example.com/protected', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE'
}
})
.then(response => response.json())
.then(data => console.log(data));
// Using Cookies
fetch('https://api.example.com/user', {
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data));
Complete Example
// Wrapper function for requests
async function sendRequest(url, options = {}) {
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
}
};
try {
const response = await fetch(url, { ...defaultOptions, ...options });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return await response.json();
}
return await response.text();
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
// Usage examples
sendRequest('https://api.example.com/data')
.then(data => console.log(data));
sendRequest('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify({ name: 'John' })
})
.then(data => console.log(data));
Using XMLHttpRequest
// GET request
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
// POST request
const xhrPost = new XMLHttpRequest();
xhrPost.open('POST', 'https://api.example.com/users', true);
xhrPost.setRequestHeader('Content-Type', 'application/json');
xhrPost.onreadystatechange = function() {
if (xhrPost.readyState === 4 && xhrPost.status === 201) {
console.log(JSON.parse(xhrPost.responseText));
}
};
xhrPost.send(JSON.stringify({
name: 'John',
email: '[email protected]'
}));
Practical Tips
1. Quick API Testing
// Run directly in the console
await fetch('https://jsonplaceholder.typicode.com/posts/1').then(r => r.json())
2. Send Files
// Select file
const input = document.createElement('input');
input.type = 'file';
input.onchange = async e => {
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
console.log(await response.json());
};
input.click();
3. Download Files
// Download as file
async function downloadJSON(data, filename = 'data.json') {
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// Usage
fetch('https://api.example.com/data')
.then(r => r.json())
.then(data => downloadJSON(data, 'result.json'));
4. Simulate Various HTTP Methods
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
methods.forEach(method => {
window[method.toLowerCase()] = (url, data = null) => {
const options = { method };
if (data) {
options.body = JSON.stringify(data);
options.headers = { 'Content-Type': 'application/json' };
}
return fetch(url, options).then(r => r.json());
};
});
// Then you can use directly
get('https://api.example.com/data')
post('https://api.example.com/users', { name: 'John' })
put('https://api.example.com/users/1', { name: 'Jane' })
delete('https://api.example.com/users/1')
Error Handling
async function safeRequest(url, options = {}) {
try {
const response = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.message || `HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Request Error:', {
url,
message: error.message,
timestamp: new Date().toISOString()
});
throw error;
}
}
// Usage
safeRequest('https://api.example.com/data')
.then(data => console.log(data))
.catch(err => console.error(err));
Common Issues
CORS Issues
If you encounter CORS errors, you can:
- Add CORS headers on the backend
- Use a proxy server
- Install a CORS Unblock extension (development only)
Timeout Settings
// Using AbortController to set a timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/slow', {
signal: controller.signal
})
.then(response => {
clearTimeout(timeoutId);
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request timed out');
}
});
Comments