function ajaxRequest(url, method = 'GET', data = null, options = {}) {
const BASE_URL = 'http://127.0.0.1:8081/';
const fullUrl = `${BASE_URL}${url}`;
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
};
const mergedOptions = { ...defaultOptions, ...options };
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
mergedOptions.body = JSON.stringify(data);
}
return fetch(fullUrl, {
method,
...mergedOptions,
})
.then(response => {
if (!response.status) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json();
} else {
return response.text();
}
})
.catch(error => {
throw new Error(`Network error: ${error}`);
});
}
module.exports = ajaxRequest;
ajaxRequest('/your/api/endpoint', 'GET')
.then(data => console.log('Received data:', data))
.catch(error => console.error('Error:', error));