Created
December 29, 2023 16:52
-
-
Save btwelch/0e14e3326ef8e8767cae38a6b8e9dea5 to your computer and use it in GitHub Desktop.
Simple client interface for javascript, using fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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