EN
Nuxt 3 - send form data using POST method and receive response
0
points
In this article, we would like to show you how to send form data using POST method and receive response in Nuxt 3.
Preview
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}`;
});