Skip to content

Instantly share code, notes, and snippets.

@AhmedHelalAhmed
Created September 26, 2021 03:04
Show Gist options
  • Save AhmedHelalAhmed/458bfc9dff1562438ffb31f31859d57d to your computer and use it in GitHub Desktop.
Save AhmedHelalAhmed/458bfc9dff1562438ffb31f31859d57d to your computer and use it in GitHub Desktop.
Using Axios Instead Of "fetch()"
import axios from 'axios'; // at the start of your <script> tag, before you "export default ..."
axios.post('https://vue-http-demo-85e9e.firebaseio.com/surveys.json', {
name: this.enteredName,
rating: this.chosenRating,
});
As you can see, with Axios, you have to write less code. It automatically sets the Content-Type header for you, it also automatically converts the body data to JSON.
BUT - as a downside - you have to add an extra package, which ultimately increases the size of the web app you're shipping in the end.
Later in the module, we'll also start reacting to the response returned by the request.
fetch() returns a Promise, hence we can use then(), catch() and async/ await there. For Axios, it's just the same - it also returns a Promise.
fetch('https://vue-http-demo-85e9e.firebaseio.com/surveys.json', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.enteredName,
rating: this.chosenRating,
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment