Last active
April 20, 2020 07:40
-
-
Save mendaomn/c6cb50f51e9a58c021de5ea03bb7b366 to your computer and use it in GitHub Desktop.
An example of how one could mimic axios' API over standard 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
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