Post Vue

Posted on  by admin
Below is a quick set of examples to show how to send HTTP POST requests from Vue to a backend API using fetch() which comes bundled with all modern browsers.

Other HTTP examples available:.

Vue + Fetch: GET. Vue + Axios: GET, POST.

React + Fetch: GET, POST, PUT, DELETE. React + Axios: GET, POST, PUT, DELETE. Angular: GET, POST, PUT, DELETE.

Blazor WebAssembly:GET, POST.

Axios: GET, POST, PUT, DELETE. Fetch: GET, POST, PUT, DELETE. This sends an HTTP POST request to the JSONPlaceholder api which is a fake online REST api that includes a /posts route that responds to POST requests with the contents of the post body and an id property.

The id from the response is assigned to the vue component data property postId so it can be displayed in the component template.

Christopher Nuccio
596

This sends the same POST request from Vue using fetch, 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).

Example Vue component at https://codesandbox.io/s/vue-fetch-http-post-request-examples-4i038?file=/app/PostRequestAsyncAwait.vue.

This sends a POST request from Vue to an invalid url on the api then assigns the error to the errorMessage component state property and logs the error to the console.

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses.
2
vpaladevpalade
1,417

POST request using fetch with error handling