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));