Languages
[Edit]
EN

Nuxt 3 - send form data using POST method and receive response

0 points
Created by:
Antonina-Trejo
447

In this article, we would like to show you how to send form data using POST method and receive response in Nuxt 3.

Preview

Nuxt 3 - submit form using POST method

Practical example

1. On frontend side, we create a simple form with textarea element which receives some text that we want to send to the server.

The textarea element uses v-model directive to bind data to form.text value returned from the element. The form.text can be later send as body.data using useFetch() method.

pages/index.vue file:

<template>
  <form>
    <textarea placeholder='Type something...' v-model="form.text" spellcheck="false"></textarea>
    <button type="button" @click="handleSubmit">Send data</button>
  </form>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
            form: {
                text: ''
            }
        }
    },
    methods: {
        async handleSubmit() {
            const { data: response } = await useFetch('/api/text', {
                method: 'post',
                body: {
                    data: this.form.text
                }
            })

            if (response) {
                alert(response.value);
            }
        }
    }
}
</script>

<style scoped>
/* ... */
</style>

2. On backend side, the server receives event object, destructures the data using readBody() method and returns some string (which we later display using alert() on frontend side).

server/api/text.js file:

export default defineEventHandler(async (event) => {
    const { data } = await readBody(event);
    return `Data from api: ${data}`;
});

Project structure

Nuxt 3 - project structure

Alternative titles

  1. Nuxt 3 - how to create and submit form and receive data from response
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join