I'm fairly new to React JS and Next JS. I was previously using the Page Router API on Next JS but then switched to use the new App Router on Next JS 13.
Previously, using the Page Router, the structure to create a single get request was to nest your "js" file under the page\api
. The server automatically create the route and return the methods + data. For example, I would export the following function:
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
Now, using the App Router and TS on Next JS 13, I understand that the mechanism is different. The API folder is nested under the app folder and you have to define a "route.ts" file with all the different GET, POST (etc..) methods:
import { NextApiRequest } from 'next';
import React from 'react';
export async function GET (request:NextApiRequest){
return new Response('John Doe')
}
I have just some problems to understand how to use this Response
object. How to you specify the structure of what you return, in my case { name: 'John Doe' }
? I want to change the response status to 400, how do I do that ?
Going forward, I have to deal 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){
//WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
//BUT THIS IS NOT WORKING WITh THE APP ROUTER
res.statusCode = 400
//- error TypeError: res.json is not a function
res.json({name:'Please provide something to search for'})
return res
}
//WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
//BUT THIS IS NOT WORKING WITh THE APP ROUTER
//- error TypeError: res.status is not a function
return res.status(200).json({anwser:'John Doe'})
})
Thanks for helping, the learning curve is a bit steep having to deal with everything at the same time (TS, NextJS 13)