search

Home  >  Q&A  >  body text

How to use useQuery() as API route parameter in Nuxt 3?

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粉860897943P粉860897943478 days ago871

reply all(2)I'll reply

  • P粉551084295

    P粉5510842952023-11-02 16:54:30

    Try using getQuery instead of useQuery

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

    reply
    0
  • P粉146080556

    P粉1460805562023-11-02 12:27:34

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

    getQuery’s h3 document

    reply
    0
  • Cancelreply