Skip to content

Instantly share code, notes, and snippets.

@mendaomn
Last active April 20, 2020 07:40
Show Gist options
  • Save mendaomn/c6cb50f51e9a58c021de5ea03bb7b366 to your computer and use it in GitHub Desktop.
Save mendaomn/c6cb50f51e9a58c021de5ea03bb7b366 to your computer and use it in GitHub Desktop.
An example of how one could mimic axios' API over standard Fetch.
const axios = {
commons: {
headers: {}
},
async _fetchWithCommons(url, options) {
const response = await fetch(url, {
...this.commons,
...options
})
const data = await response.json()
return {
...response,
data
}
},
get(url, options) {
return this._fetchWithCommons(url, {
method: 'get',
...options
})
},
post(url, data, options) {
return this._fetchWithCommons(url, {
method: 'post',
body: JSON.stringify(data),
...options
})
}
}
// Usage
axios.commons.headers['Authorization'] = `Bearer ${token}`
const { data } = await axios.post('/contacts', {
name: 'Alessandro',
surname: 'Menduni'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment