英文:
How to correctly use the API routes in the Next JS 13 Using App Router framework
问题
我相对于React JS和Next.js还比较新。我以前在Next.js中使用Page Router API,但后来切换到了Next.js 13中的新App Router。
以前,使用Page Router,创建单个GET请求的结构是将您的"JS"文件嵌套在page\api
下。服务器会自动创建路由并返回方法和数据。例如,我会导出以下函数:
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
现在,使用App Router和Next.js 13中的TS,我了解到机制不同了。API文件夹嵌套在app文件夹下,您必须定义一个"route.ts"文件,其中包含所有不同的GET、POST等方法:
import { NextApiRequest } from 'next';
import React from 'react';
export async function GET (request: NextApiRequest){
return new Response('John Doe')
}
我有一些问题,不太明白如何使用这个Response
对象。如何指定返回的结构,例如我的情况{ name: 'John Doe' }
?我想将响应状态更改为400,应该如何做?
接下来,我必须处理一个POST请求。
import type { NextApiRequest, NextApiResponse } from 'next';
type MyData = {
name: string;
}
export async function POST(
req: NextApiRequest,
res: NextApiResponse<MyData>
){
const { nameLookup } = req.body
if (!nameLookup) {
//如果我使用Page Router,我想要做的事情
//但是在App Router中不起作用
res.statusCode = 400
//- 错误 TypeError: res.json 不是一个函数
res.json({ name: '请提供要搜索的内容' })
return res
}
//如果我使用Page Router,我想要做的事情
//但是在App Router中不起作用
//- 错误 TypeError: res.status 不是一个函数
return res.status(200).json({ answer: 'John Doe' });
}
谢谢您的帮助,学习曲线有点陡,需要同时处理很多东西(TS、Next.js 13)。
英文:
I'm fairly new to React JS and Next.js. I was previously using the Page Router API in Next.js but then switched to use the new App Router in 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 creates the route and returns 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 some problems understanding 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, Next.js 13)
答案1
得分: 4
以下是根据您的路由示例进行的示例:
export async function POST(request: NextRequest) {
const { nameLookup }: MyData = await request.json();
if (!nameLookup) {
return new NextResponse(
JSON.stringify({ name: "请提供要搜索的内容" }),
{ status: 400 }
);
}
return new NextResponse(JSON.stringify({ answer: "约翰·多" }), {
status: 200,
});
}
请注意,在发布到Stack Overflow之前,您应该自行进行一些研究。查看应用程序路由器文档此处可能已经足够了。
英文:
Here is an example based on your route:
export async function POST(request: NextRequest) {
const { nameLookup }: MyData = await request.json();
if (!nameLookup) {
return new NextResponse(
JSON.stringify({ name: "Please provide something to search for" }),
{ status: 400 }
);
}
return new NextResponse(JSON.stringify({ answer: "John Doe" }), {
status: 200,
});
}
Please not that you should do some research on your own before posting to stack overflow. A look at the app router documentation here would've probably sufficed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论