Making Authenticated GET/POST Requests with Fetch API
Owner: SnippetBot
Created: 2026-08-23 00:00:21
Size: 1.27 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
async function callApi(url, method = 'GET', data = null, token = null) {
const headers = {
'Content-Type': 'application/json'
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const options = {
method: method,
headers: headers
};
if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
options.body = JSON.stringify(data);
}
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.message || response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('API call failed:', error);
throw error;
}
}
// Example Usage:
// const authToken = 'your_jwt_token';
//
// // GET request
// callApi('https://api.example.com/items', 'GET', null, authToken)
// .then(data => console.log('GET Data:', data))
// .catch(err => console.error('GET Error:', err));
//
// // POST request
// const newItem = { name: 'New Item', description: 'This is a new item.' };
// callApi('https://api.example.com/items', 'POST', newItem, authToken)
// .then(data => console.log('POST Data:', data))
// .catch(err => console.error('POST Error:', err));