How to get params from api
Unanswered
Saltwater Crocodile posted this in #help-forum
Saltwater CrocodileOP
Im trying to get params from api for example if the req is: https://localhost:3000/api/get/abcd123
I want to get abcd123
My folder structure is api/get/[shortid]
this is my code:
Now shortId is null or empty
I want to get abcd123
My folder structure is api/get/[shortid]
this is my code:
import { NextRequest, NextResponse } from 'next/server';
import shortUrl from "@/models/shortUrl.model";
export async function GET( req: NextRequest) {
const shortId = req.nextUrl.searchParams;
console.log('aaaa ' + shortId)
const short = await shortUrl.findOne({ shortId }).lean();
if (!short){
return NextResponse.json(
{
statusCode: 404,
error: {
'message': 'Url not found'
}
},
{ status: 404 }
)
}
return NextResponse.redirect(short.destination);
}Now shortId is null or empty
2 Replies
Saltwater CrocodileOP
So I managed to find a solution and change to this: const shortId = req.url.slice(req.url.lastIndexOf('/') + 1);
it works but I doubt this is the best way