Home > Enterprise >  How to use useQuery() for API route parameters in Nuxt 3?
How to use useQuery() for API route parameters in Nuxt 3?

Time:11-22

I'm following a guide in which api routes are built like so:

1 create server/api/route.js file:

export default defineEventHandler((event) => {

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

2 use api route in component like so:

<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 a query parameter in 1.:

export default defineEventHandler((event) => {

    const { name } = useQuery(event)

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

and call it in a component 2.:

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

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

the message property is empty. It seems that useQuery(event) produces an empty variable. Any idea why this is not working?

CodePudding user response:

Try getQuery instead of useQuery

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

CodePudding user response:

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

h3 Docs for getQuery

  • Related