Skip to content

Instantly share code, notes, and snippets.

@btwelch
Created December 29, 2023 16:52
Show Gist options
  • Save btwelch/0e14e3326ef8e8767cae38a6b8e9dea5 to your computer and use it in GitHub Desktop.
Save btwelch/0e14e3326ef8e8767cae38a6b8e9dea5 to your computer and use it in GitHub Desktop.
Simple client interface for javascript, using fetch
export class Client {
Success = 'Success';
Error = 'Error';
async getData(path) {
let fullPath = path;
const result = await fetch(fullPath, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
});
const resultJson = await result.json();
if (resultJson.result?.redirect_url) {
window.location = resultJson.result?.redirect_url;
} else {
return resultJson;
}
}
async postData(path, params) {
const token = document.querySelector('meta[name="csrf-token"]').content;
let fullPath = path;
const result = await fetch(fullPath, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
"X-CSRF-Token": token
},
body: JSON.stringify(params)
});
const resultJson = await result.json();
if (resultJson.result?.redirect_url) {
window.location = resultJson.result?.redirect_url;
} else {
return resultJson;
}
}
}
const client = new Client();
export default client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment