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

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

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:

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

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

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 路由

import { NextApiRequest } from &#39;next&#39;;
import React from &#39;react&#39;;


export async function GET (request:NextApiRequest){
    return new Response(&#39;John Doe&#39;)
} 

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.

import type {NextApiRequest, NextApiResponse} from &#39;next&#39;

type MyData ={
    name:string
}

export async function POST(
    req: NextApiRequest, 
    res: NextApiResponse&lt;Data&gt;
){
    
    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:&#39;Please provide something to search for&#39;})
        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:&#39;John Doe&#39;})
})

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: &quot;Please provide something to search for&quot; }),
      { status: 400 }
    );
  }
  
  return new NextResponse(JSON.stringify({ answer: &quot;John Doe&quot; }), {
    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.

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:

确定