How to get route parameters from Nuxt 3 server

Viewed 1513

I have one of the following API URLs. At the end of the day for my use case, it doesn't matter which of these URLs I would have to use, but currently neither work.

http://localhost:3000/api/track/TRACKID

or

http://localhost:3000/api/track?id=TRACKID

How would I get TRACKID in the APIs code? The following code results in undefined.

export default async (req: IncomingMessage, res: ServerResponse) => {
    console.log(req.id);
};

I tried to set up the file for the first URL in the following way, but that was unsuccessful as well. It just resulted in the URL being http://localhost:3000/api/track/[id]

PROJECT/server/api/track/[id].ts

For the second URL I used the following set up.

PROJECT/server/api/track.ts
3 Answers
import { useQuery } from 'h3'
export default (req, res) => {
    const { id } = useQuery(req)
}

https://github.com/unjs/h3 is the server putting the api together.

import * as url from "url";

const params = url.parse(req.url as string, true).query;
const {id} = params

For newer nuxt3 dev's

The h3 route now give you a CompatibilityEvent instead of using req and res.

Therefore you can use it like this:

export default defineEventHandler(async (event) => {
     const id = event.context.params.id;

     // Use the id here
});
Related