How to use useQuery() as API route parameter in Nuxt 3?
P粉860897943
P粉860897943 2023-11-01 19:50:53
0
2
767

I'm following a guide where the api routes are built like this:

1 Create server/api/route.js file:

export default defineEventHandler((event) => {

    return {
        message: `hello api route`
    }
})

2 Use api routing in the component as follows:

<script setup>
const { data: message } = await useFetch('/api/route')
</script>

<template>
  <div>
    <p>api data {{ message }}</p>
  </div>
</template>

This works, but when I try to add the query parameter in 1.:

export default defineEventHandler((event) => {

    const { name } = useQuery(event)

    return {
        message: `hello api name parameter ${name}`
    }
})

And call it in the component2.:

<script setup>
const { data: message } = await useFetch('/api/route?name=mario')
</script>

<template>
  <div>
    <p>api data {{ message }}</p>
  </div>
</template>

message The attribute is empty. It seems useQuery(event) produces an empty variable. Any idea why this doesn't work?

P粉860897943
P粉860897943

reply all(2)
P粉551084295

Try using getQuery instead of useQuery

export default defineEventHandler((event) => {
  const { name } = getQuery(event);
  return {
      message: `hello api name parameter ${name}`,
  };
});
P粉146080556

useQuery(event) is no longer supported. You can use getQuery(event)

getQuery’s h3 document

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!