I'm using nuxt 3 for a project and I want to make a request to a typescript file in /server/api/
directory. But when I do in my file app.vue:
<script setup lang="ts">
const createPerson = async () => {
console.log('create person')
const data = await useAsyncData('createPerson', () => $fetch('/api/file', {
method: 'POST',
headers: useRequestHeaders(['cookie']),
body: JSON.stringify({
lastname: fields.value.lastname,
firstname: fields.value.firstname,
age: fields.value.age,
x: fields.value.x,
y: fields.value.y,
bio: fields.value.bio
})
}))
console.log(data)
}
</script>
and when I call this function createPerson from:
<button @click="createPerson">Apply</button>
my app fetch '/api/file' only one time and not re-fetching. If I use refresh function gived with useAsyncData, the first time I click on button I have two fetch and after one fetch.
HOLLY JESUS !!! That's simple just set initialCache to false in useAsyncData parameters like this:
<script setup lang="ts">
const createPerson = async () => {
console.log('create person')
const data = await useAsyncData('createPerson', () => $fetch('/api/file', {
method: 'POST',
headers: useRequestHeaders(['cookie']),
body: JSON.stringify({
lastname: fields.value.lastname,
firstname: fields.value.firstname,
age: fields.value.age,
x: fields.value.x,
y: fields.value.y,
bio: fields.value.bio
})
}), { initialCache: false })
console.log(data)
}
</script>
If you don't need the extra functionality of useAsyncData
/ useFetch
, you can simplify by just using the $fetch
utility on its own.
<script lang="ts" setup>
const createPerson = async () => {
const data = await $fetch('/api/file', {
method: 'POST',
headers: useRequestHeaders(['cookie']),
body: {
lastname: fields.value.lastname,
firstname: fields.value.firstname,
age: fields.value.age,
x: fields.value.x,
y: fields.value.y,
bio: fields.value.bio,
},
})
// ...
}
</script>
You also shouldn't need to use JSON.stringify
, h3
provides the useBody
composable that will parse the body of a request.
// server/api/file.ts
export default defineEventHandler(async ({ req }) => {
const { age, bio, firstname, lastname, x, y } = await useBody(req)
// ...
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.