How to use useQuery() for API route parameters in Nuxt 3?
Asked Answered
S

3

14

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?

Smoothshaven answered 21/11, 2022 at 9:45 Comment(0)
M
40

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

h3 Docs for getQuery

Malapert answered 21/11, 2022 at 17:40 Comment(2)
useBody(event) is also no longer supported. Replacement is readBody(event)Leucoderma
that work tanksBedcover
L
17

Try getQuery instead of useQuery

export default defineEventHandler((event) => {
  const { name } = getQuery(event);
  return {
      message: `hello api name parameter ${name}`,
  };
});
Lovelovebird answered 21/11, 2022 at 17:38 Comment(0)
O
3

Please checkout the docs too:

useBody(event) => readBody(event) https://nuxt.com/docs/guide/directory-structure/server#body-handling

useQuery(event) => getQuery(event) https://nuxt.com/docs/guide/directory-structure/server#query-parameters

Odalisque answered 16/2 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.