// request.js
const BASE_URL = 'https://api.example.com';
const handleResponse = async (response) => {
if (response.ok) {
const data = await response.json();
return data;
} else {
const error = await response.text();
throw new Error(error);
}
};
const request = async (url, options) => {
try {
const response = await fetch(`${BASE_URL}${url}`, options);
const data = await handleResponse(response);
return data;
} catch (error) {
console.error('リクエストが失敗しました:', error);
throw error;
}
};
export const get = (url, headers = {}) => {
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
...headers,
},
};
return request(url, options);
};
export const post = (url, body, headers = {}) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
};
return request(url, options);
};
export const put = (url, body, headers = {}) => {
const options = {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...headers,
},
body: JSON.stringify(body),
};
return request(url, options);
};
export const del = (url, headers = {}) => {
const options = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
...headers,
},
};
return request(url, options);
};