As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13.
Previously, with the Page Router, creating a single GET request involved nesting your "JS" file under the page\api
directory. The server would then automatically generate the route and handle the methods and data retrieval. For instance, an exported function would look like:
https://i.stack.imgur.com/CUdpe.jpg
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
Now, with the App Router and TypeScript in Next.js 13, the approach is different. The API folder is nested under the app directory, requiring you to define a "route.ts" file containing various HTTP request handlers such as GET and POST:
https://i.stack.imgur.com/sI91v.jpg
import { NextApiRequest } from 'next';
import React from 'react';
export async function GET(request:NextApiRequest){
return new Response('John Doe')
}
I'm currently struggling to comprehend how to use the Response
object and specify the structure of the returned data, such as { name: 'John Doe' }
. Furthermore, if I want to change the response status to 400, how would I go about doing that?
My next challenge involves dealing with a POST request.
import type {NextApiRequest, NextApiResponse} from 'next'
type MyData ={
name:string
}
export async function POST(
req: NextApiRequest,
res: NextApiResponse<Data>
){
const {nameLookup} = req.body
if(!nameLookup){
res.statusCode = 400
res.json({name:'Please provide something to search for'})
return res
}
return res.status(200).json({anwser:'John Doe'})
})
I appreciate any assistance as I navigate through this steep learning curve of incorporating TypeScript and Next.js 13 simultaneously.