Below is a quick set of examples to show how to send HTTP POST requests from Vue to a backend API using the axios
HTTP client which is available on npm.
Other HTTP examples available:
With the npm CLI: npm install axios
With the yarn CLI: yarn add axios
This sends an HTTP POST request to the Reqres api which is a fake online REST api that includes a generic /api/<resource>
route that responds to POST
requests for any <resource>
with the contents of the post body and a dynamic id property. This example sends an article
object to the /api/articles
route and then assigns the id from the response to the vue component data property articleId
so it can be displayed in the component template.
created() {
// Simple POST request with a JSON body using axios
const article = { title: "Vue POST Request Example" };
axios.post("https://reqres.in/api/articles", article)
.then(response => this.articleId = response.data.id);
}
Example Vue component at https://codesandbox.io/s/vue-axios-http-post-request-examples-ecqqn?file=/app/PostRequest.vue
This sends the same POST request from Vue using axios, but this version uses an async
function and the await
javascript expression to wait for the promises to return (instead of using the promise then()
method as above).
async created() {
// POST request using axios with async/await
const article = { title: "Vue POST Request Example" };
const response = await axios.post("https://reqres.in/api/articles", article);
this.articleId = response.data.id;
}
Example Vue component at https://codesandbox.io/s/vue-axios-http-post-request-examples-ecqqn?file=/app/PostRequestAsyncAwait.vue
#vue #axios #programming #vue.js