How to use req.query?.id
Answered
Waterman posted this in #help-forum
WatermanOP
I get this error when trying to use query as in the tutorial but I suspect it might be outdated
Error:
Property 'query' does not exist on type 'Request'
I am not sure that this:
Is the best way of doing it either, so would be great with some tips
app/basprodukter/redigera/[...]/page.tsx:
app/api/basproducts/route.js:
Error:
Property 'query' does not exist on type 'Request'
I am not sure that this:
const pathname = usePathname();
const parts = pathname.split("/");
const id = parts[parts.length - 1];
console.log(id);Is the best way of doing it either, so would be great with some tips
app/basprodukter/redigera/[...]/page.tsx:
"use client";
import BaseLayout from "@/components/baselayout";
import axios from "axios";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
export default function page() {
const pathname = usePathname();
const parts = pathname.split("/");
const id = parts[parts.length - 1];
console.log(id);
useEffect(() => {
if (!id) {
return;
}
axios.get("/api/basproducts?id=" + id).then((response) => {
console.log(response.data);
});
}, [id]);
return <BaseLayout>rediger produkt</BaseLayout>;
}app/api/basproducts/route.js:
export const GET = async (req: Request, res: Response) => {
const { method } = req;
await mongooseConnect();
if (method === "GET") {
if (req.query?.id) { "<<<<---error---Property 'query' does not exist on type 'Request'"
return NextResponse.json(await BasProdukt.findOne({ _id: req.query.id }));
}
}
};9 Replies
the get function should also only have one parameter, which is the request
the response doesnt need to be there
WatermanOP
oh okay thanks, do you think you could modify my code just a little in order for me to understand a little better how to do it
would be very nice
Asiatic Lion
export const GET = async (request: Request) => {
const queryId = request.nextUrl.searchParams.get('id');
await mongooseConnect();
if (queryId) {
return NextResponse.json(await BasProdukt.findOne({ _id: queryId }));
} else {
return NextResponse.json({ error: 'No Id' })
}
};the function only works for get requests so no point to add the extra if statement
WatermanOP
oh okay thats true, thanks alot man
Asiatic Lion
welcome
Answer