import axios from 'axios';
const API = axios.create({ baseURL: "YOUR_API_BASE_URL_HERE", responseType: 'json'});
const setHeaders = (token, contentType) => {
let headers = {
Accept: "application/json"
}
if (contentType) headers["Content-Type"] = contentType;
if (token) headers.Authorization = `Bearer ${token}`;
return headers;
}
export const ApiRequest = {
get: ({endpoint, token = null, contentType = null, success, failure}) => {
return API.get(endpoint, setHeaders(token, contentType))
.then(async (response) => await success(response))
.catch((error) => failure(error));
},
post: ({endpoint, token = null, contentType = null, data, success, failure}) => {
return API.post(endpoint, data, setHeaders(token, contentType))
.then(async (response) => await success(response))
.catch((error) => failure(error));
},
delete: ({endpoint, token = null, contentType = null, success, failure}) => {
return API.delete(endpoint, setHeaders(token, contentType))
.then(async (response) => await success(response))
.catch((error) => failure(error));
}
};
Here's an example implementation
ApiRequest.post({
endpoint: 'auth/login',
// token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9',
// contentType: 'application/json',
data: {},
success: (response) => { },
failure: (error) => { }
});