Created
September 26, 2021 03:04
-
-
Save AhmedHelalAhmed/458bfc9dff1562438ffb31f31859d57d to your computer and use it in GitHub Desktop.
Using Axios Instead Of "fetch()"
This file contains hidden or 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
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, | |
}); |
This file contains hidden or 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
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. |
This file contains hidden or 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
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