API route with handler not working
Unanswered
MD20M posted this in #help-forum
MD20MOP
So I've been trying to get Next.js API routes working with Passport.js. I tried using the routes with just the path and then the route.ts file. The problem there was that I needed to get a response function with a
.end() method. The NextApiResponse supports that but I can't figure out how I could use that with this setup since it works with NextResponse. So I tried making the old API route by placing the file into pages/api and then sending a post request with pages/api/example but I just keep getting a 404 error and I don't now how to fix that. I am probably missing something very obvious. Thanks in advance!1 Reply
Are you using the pages router? or the app router?
example app router api:
app/api/hello/route.ts
example pages router api:
pages/api/hello.ts
example app router api:
app/api/hello/route.ts
import { NextRequest, NextResponse } from "next/server";
// Post request
export async function POST(request: NextRequest, response: NextResponse) {
const { searchParams } = new URL(request.url)
const name = searchParams.get('name')
if (!name) {
return new Response('Missing parameters', { status: 400
});
}
return new Response(`Hello ${name}!`, {
status: 200
});
}
// Post request
export async function GET(request: NextRequest, response: NextResponse) {
return new Response('Hello!', {
status: 200
});
}example pages router api:
pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
// Get & Post request
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
if (req.method === 'POST') {
// handle post.
} else {
// handle all other methods
}
res.status(200).json({ message: 'Hello from Next.js!'})
}