如何在 Next JS 13 中正确使用 App Router 框架中的 API 路由

huangapple go评论117阅读模式
英文:

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下。服务器会自动创建路由并返回方法和数据。例如,我会导出以下函数:

  1. export default (req, res) => {
  2. res.statusCode = 200
  3. res.json({ name: 'John Doe' })
  4. }

现在,使用App Router和Next.js 13中的TS,我了解到机制不同了。API文件夹嵌套在app文件夹下,您必须定义一个"route.ts"文件,其中包含所有不同的GET、POST等方法:

  1. import { NextApiRequest } from 'next';
  2. import React from 'react';
  3. export async function GET (request: NextApiRequest){
  4. return new Response('John Doe')
  5. }

我有一些问题,不太明白如何使用这个Response对象。如何指定返回的结构,例如我的情况{ name: 'John Doe' }?我想将响应状态更改为400,应该如何做?

接下来,我必须处理一个POST请求。

  1. import type { NextApiRequest, NextApiResponse } from 'next';
  2. type MyData = {
  3. name: string;
  4. }
  5. export async function POST(
  6. req: NextApiRequest,
  7. res: NextApiResponse<MyData>
  8. ){
  9. const { nameLookup } = req.body
  10. if (!nameLookup) {
  11. //如果我使用Page Router,我想要做的事情
  12. //但是在App Router中不起作用
  13. res.statusCode = 400
  14. //- 错误 TypeError: res.json 不是一个函数
  15. res.json({ name: '请提供要搜索的内容' })
  16. return res
  17. }
  18. //如果我使用Page Router,我想要做的事情
  19. //但是在App Router中不起作用
  20. //- 错误 TypeError: res.status 不是一个函数
  21. return res.status(200).json({ answer: 'John Doe' });
  22. }

谢谢您的帮助,学习曲线有点陡,需要同时处理很多东西(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:

如何在 Next JS 13 中正确使用 App Router 框架中的 API 路由

  1. export default (req, res) =&gt; {
  2. res.statusCode = 200
  3. res.json({ name: &#39;John Doe&#39; })
  4. }

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:

如何在 Next JS 13 中正确使用 App Router 框架中的 API 路由

  1. import { NextApiRequest } from &#39;next&#39;;
  2. import React from &#39;react&#39;;
  3. export async function GET (request:NextApiRequest){
  4. return new Response(&#39;John Doe&#39;)
  5. }

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: &#39;John Doe&#39; } ? I want to change the response status to 400, how do I do that?

Going forward, I have to deal with a POST request.

  1. import type {NextApiRequest, NextApiResponse} from &#39;next&#39;
  2. type MyData ={
  3. name:string
  4. }
  5. export async function POST(
  6. req: NextApiRequest,
  7. res: NextApiResponse&lt;Data&gt;
  8. ){
  9. const {nameLookup} = req.body
  10. if(!nameLookup){
  11. //WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
  12. //BUT THIS IS NOT WORKING WITH THE APP ROUTER
  13. res.statusCode = 400
  14. //- error TypeError: res.json is not a function
  15. res.json({name:&#39;Please provide something to search for&#39;})
  16. return res
  17. }
  18. //WHAT I WOULD LIKE TO DO IF I WAS USING THE PAGE ROUTER
  19. //BUT THIS IS NOT WORKING WITH THE APP ROUTER
  20. //- error TypeError: res.status is not a function
  21. return res.status(200).json({anwser:&#39;John Doe&#39;})
  22. })

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

以下是根据您的路由示例进行的示例:

  1. export async function POST(request: NextRequest) {
  2. const { nameLookup }: MyData = await request.json();
  3. if (!nameLookup) {
  4. return new NextResponse(
  5. JSON.stringify({ name: "请提供要搜索的内容" }),
  6. { status: 400 }
  7. );
  8. }
  9. return new NextResponse(JSON.stringify({ answer: "约翰·多" }), {
  10. status: 200,
  11. });
  12. }

请注意,在发布到Stack Overflow之前,您应该自行进行一些研究。查看应用程序路由器文档此处可能已经足够了。

英文:

Here is an example based on your route:

  1. export async function POST(request: NextRequest) {
  2. const { nameLookup }: MyData = await request.json();
  3. if (!nameLookup) {
  4. return new NextResponse(
  5. JSON.stringify({ name: &quot;Please provide something to search for&quot; }),
  6. { status: 400 }
  7. );
  8. }
  9. return new NextResponse(JSON.stringify({ answer: &quot;John Doe&quot; }), {
  10. status: 200,
  11. });
  12. }

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.

huangapple
  • 本文由 发表于 2023年6月6日 04:07:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定