Published: February 02 2023

Vue 3 - HTTP POST Request Examples

Tutorial built with Vue 3.2.45

Below is a quick set of examples to show how to send HTTP POST requests from Vue 3 to a backend API using fetch() which comes built into all modern browsers.

Other Vue 3 HTTP examples: GET, PUT, PATCH, DELETE.

Tutorial contents


Simple HTTP POST request with a JSON body

This sends an HTTP POST request to the Test JSON API which is a fake online REST API that includes a /products route that responds to POST requests with the contents of the post body plus a new id property and createdAt date property.

After the JSON data is fetched from the API it is assigned to the product ref variable and rendered in the component template.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// Simple POST request with a JSON body using fetch
const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Vue 3 POST Request Example' })
};
fetch('https://testapi.jasonwatmore.com/products', requestOptions)
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">Simple POST Request</h5>
        <div class="card-body">New product id: {{product?.id}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-post-request-examples?file=src%2FPostRequest.vue


HTTP POST request with async/await

This sends the same POST request from Vue 3 using fetch, but this version uses a couple of top-level await expressions in the <script setup> block to wait for the promises to return (instead of using the promise then() method as above). The top-level await results in the setup function being compiled as async setup().

NOTE: async components must be wrapped with the Vue 3 <Suspense> component in order to render. Suspense is still an experimental feature at the time I'm writing this so the way it works may change in future. For more info see https://vuejs.org/guide/built-ins/suspense.html.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// POST request using fetch with async/await
const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Vue 3 POST Request Example" })
};
const response = await fetch('https://testapi.jasonwatmore.com/products', requestOptions);
const data = await response.json();
product.value = data;
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">POST Request with Async/Await</h5>
        <div class="card-body">New product id: {{product?.id}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-post-request-examples?file=src%2FPostRequestAsyncAwait.vue


POST request with HTTP headers set

This sends the same POST request again from Vue 3 using fetch with a couple of extra headers set, the HTTP Authorization header and a custom header My-Custom-Header.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// POST request using fetch with set headers
const requestOptions = {
    method: 'POST',
    headers: { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ name: 'Vue 3 POST Request Example' })
};
fetch('https://testapi.jasonwatmore.com/products', requestOptions)
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">POST Request with Set Headers</h5>
        <div class="card-body">New product id: {{product?.id}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-post-request-examples?file=src%2FPostRequestSetHeaders.vue


HTTP POST request with error handling

This sends a POST request from Vue 3 to an invalid url on the API then assigns the error to the errorMessage ref variable and logs the error to the console.

Error handling with the Fetch API

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block. For more info see Fetch - Error Handling for Failed HTTP Responses and Network Errors.

<script setup>
import { ref } from 'vue';

const product = ref(null);
const errorMessage = ref(null);

// POST request using fetch with error handling
const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Vue 3 POST Request Example' })
};
fetch('https://testapi.jasonwatmore.com/invalid-url', requestOptions)
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson && await response.json();

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        product.value = data;
    })
    .catch(error => {
        errorMessage.value = error;
        console.error("There was an error!", error);
    });
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">POST Request with Error Handling</h5>
        <div class="card-body">Error message: {{errorMessage}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-post-request-examples?file=src%2FPostRequestErrorHandling.vue

 


Need Some Vue 3 Help?

Search fiverr for freelance Vue 3 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by