Consider this Vue 3 component using the Composition API. What will be the console output after submitting the form?
<template> <form @submit.prevent="submitForm"> <input v-model="username" placeholder="Username" /> <button type="submit">Submit</button> </form> </template> <script setup> import { ref } from 'vue' const username = ref('') async function submitForm() { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: username.value }) }) const data = await response.json() console.log(data.message) } </script>
Look at how username is used and how fetch is called with await.
The component uses ref to make username reactive. The submitForm function sends a POST request with JSON body and logs the server's response message.
Choose the code snippet that correctly sends a POST request with JSON data inside a Vue method.
Remember to set the correct Content-Type header and stringify the body.
Option B correctly sets the header to application/json and stringifies the body. Options C and D send the body as an object, which is invalid. Option B misses the header.
This Vue component sends a POST request to an external API but gets a CORS error in the browser. What is the most likely cause?
<script setup> import { ref } from 'vue' const data = ref('') async function sendData() { const res = await fetch('https://external.api/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: data.value }) }) console.log(await res.json()) } </script>
Think about browser security rules for cross-origin requests.
CORS errors happen when the server does not permit requests from your site. The client code is correct; the server must allow the origin.
In this Vue component, what will be the value of status after the form is submitted and the server responds with { success: true }?
<template> <form @submit.prevent="submit"> <input v-model="input" /> <button type="submit">Send</button> </form> <p>{{ status }}</p> </template> <script setup> import { ref } from 'vue' const input = ref('') const status = ref('idle') async function submit() { status.value = 'sending' const res = await fetch('/api/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ input: input.value }) }) const data = await res.json() if (data.success) { status.value = 'success' } else { status.value = 'error' } } </script>
Look at how status changes after the fetch call.
The code sets status to 'sending' before the request, then updates it to 'success' if the server responds with { success: true }.
Which is the best explanation for using async/await when sending POST requests in Vue form submission?
Think about how async/await affects code flow and readability.
Async/await lets you write asynchronous code that looks like normal sequential code. It waits for the fetch to complete before moving on, improving clarity.