最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can you have multiple API routes in one file NextJS (Pages directory) - Stack Overflow

programmeradmin2浏览0评论

I'm new to NextJS and am trying to learn the API. In the default hello.js file inside of the api folder there is an export default function which returns a JSON response. So now if I want to add another route would I have to create a separate file for that or just add a function below to do so? I would like to just be able to add more functions to create more routes.

I'm new to NextJS and am trying to learn the API. In the default hello.js file inside of the api folder there is an export default function which returns a JSON response. So now if I want to add another route would I have to create a separate file for that or just add a function below to do so? I would like to just be able to add more functions to create more routes.

Share Improve this question edited Jul 3, 2023 at 17:08 Kannu Mandora 6914 silver badges17 bronze badges asked Aug 10, 2022 at 15:35 user16949958user16949958
Add a ment  | 

2 Answers 2

Reset to default 4

Yes you can have dynamic api routes just like you can have dynamic pages!

From the docs

For example, the API route pages/api/post/[pid].js has the following code:

export default function handler(req, res) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}

Now, a request to /api/post/abc will respond with the text: Post: abc.

So you could definitely have different functions based on the api route you are trying to get to. You could use a switch or whatever works for you.

Docs

i think you want to have different http method for an api route, right

you can with check method

 export default function handler(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}

发布评论

评论列表(0)

  1. 暂无评论