POST requests send data from a form to a server safely. They help save or update information.
POST requests for form submission in Vue
<template> <form @submit.prevent="submitForm"> <!-- form inputs here --> </form> </template> <script setup> import { ref } from 'vue' const formData = ref({}) async function submitForm() { const response = await fetch('URL', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData.value) }) // handle response } </script>
Use @submit.prevent to stop the page from reloading on submit.
Always set Content-Type to application/json when sending JSON data.
<form @submit.prevent="submitForm"> <input v-model="formData.name" placeholder="Name" /> <button type="submit">Send</button> </form>
async function submitForm() { const response = await fetch('/api/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData.value) }) const result = await response.json() console.log(result.message) }
This Vue component shows a simple contact form. When submitted, it sends the data with a POST request. It shows messages about the sending status. The form uses accessible labels and live region for updates.
<template>
<main>
<h1>Contact Us</h1>
<form @submit.prevent="submitForm" aria-label="Contact form">
<label for="name">Name:</label>
<input id="name" v-model="formData.name" required aria-required="true" />
<label for="email">Email:</label>
<input id="email" type="email" v-model="formData.email" required aria-required="true" />
<button type="submit">Submit</button>
</form>
<p role="status" aria-live="polite">{{ message }}</p>
</main>
</template>
<script setup>
import { ref } from 'vue'
const formData = ref({ name: '', email: '' })
const message = ref('')
async function submitForm() {
message.value = 'Sending...'
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData.value)
})
if (response.ok) {
message.value = 'Form submitted successfully!'
formData.value = { name: '', email: '' }
} else {
message.value = 'Failed to submit form.'
}
} catch {
message.value = 'Error sending form.'
}
}
</script>Always handle errors to inform users if the submission fails.
Use aria-label and aria-live for better accessibility.
Reset form fields after successful submission to clear inputs.
POST requests send form data safely to servers.
Use Vue's @submit.prevent to control form submission.
Show clear messages to users about submission status.
Practice
Solution
Step 1: Understand Vue event modifiers
Vue provides event modifiers like.preventto stop default browser actions.Step 2: Identify the correct event for form submission
The form submission event issubmit, so@submit.preventstops the default submit and allows custom handling.Final Answer:
@submit.prevent -> Option DQuick Check:
Use @submit.prevent to control form submit [OK]
- Using @click.prevent on form instead of @submit.prevent
- Trying to use v-model.prevent which doesn't exist
- Using @input.prevent which is for input events
Solution
Step 1: Identify the correct HTTP method for sending data
POST is used to send data to the server, so method must be 'POST'.Step 2: Use the correct property for sending JSON data
fetch expects the data in thebodyproperty as a string, so useJSON.stringify(data).Final Answer:
fetch('/api', { method: 'POST', body: JSON.stringify(data) }) -> Option AQuick Check:
POST with JSON.stringify in body = fetch('/api', { method: 'POST', body: JSON.stringify(data) }) [OK]
- Using method GET when sending data
- Passing data directly without JSON.stringify
- Using 'data' property instead of 'body'
async submitForm() {
const response = await fetch('/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.formData)
});
if (response.ok) {
console.log('Success');
} else {
console.log('Failed');
}
}Solution
Step 1: Understand fetch response status
When the server responds with status 200,response.okis true.Step 2: Check the conditional logging
Ifresponse.okis true, it logs 'Success'. Otherwise, it logs 'Failed'.Final Answer:
Success -> Option BQuick Check:
response.ok true means 'Success' logged [OK]
- Confusing response.ok with response.status
- Expecting 'Failed' on status 200
- Missing await causing no output
submit() {
fetch('/api', {
method: 'POST',
body: this.formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
}Solution
Step 1: Check how formData is sent in fetch
fetch expects the body to be a string for JSON data, sothis.formDatamust be stringified.Step 2: Identify missing JSON.stringify
WithoutJSON.stringify(this.formData), the server may not receive data correctly.Final Answer:
Missing JSON.stringify for body data -> Option AQuick Check:
Body must be JSON string, not raw object [OK]
- Sending raw object instead of JSON string
- Forgetting method: 'POST' (not the case here)
- Not handling errors with catch
Solution
Step 1: Check correct JSON stringification
Options A and C stringify the form data correctly; B and D do not.Step 2: Identify correct async handling
submit() { fetch('/submit', { method: 'POST', body: JSON.stringify(this.form) }) .then(res => res.json()) .then(data => { if (data.success) alert('Submitted!'); }); }uses promise chaining correctly without async/await, which is valid.async submit() { const res = await fetch('/submit', { method: 'POST', body: JSON.stringify(this.form) }); const data = await res.json(); if (data.success) alert('Submitted!'); }uses async/await but misses headers for JSON content.Step 3: Consider headers for JSON content
submit() { fetch('/submit', { method: 'POST', body: JSON.stringify(this.form) }) .then(res => res.json()) .then(data => { if (data.success) alert('Submitted!'); }); }is the best because it correctly stringifies and processes JSON response; headers are optional but recommended.Final Answer:
Option C correctly submits and checks JSON success -> Option CQuick Check:
Stringify data and check JSON success in then() [OK]
- Not stringifying form data before sending
- Missing headers for JSON content-type
- Mixing async/await and then() incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
