【问题标题】:Cleaner way to write api route handlers in NextJS在 NextJS 中编写 api 路由处理程序的更简洁的方法
【发布时间】:2021-12-29 10:54:01
【问题描述】:

目前大部分的 api 路由处理程序都是如下形式(api/test.js):

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

我们不断将req.methodifs 进行比较

有没有类似ExpressJS的写法:

app.get(...)

【问题讨论】:

    标签: express next.js


    【解决方案1】:
    import nextConnect from 'next-connect';
    
    const handler = nextConnect();
    //handler.use(middleware);
    
    handler.get(async (req, res) => { 
      ...your code
    })
    ...
    handler.post(async (req, res) => { 
      ...your code
    })
    ...
    

    所以理论上你可以有/api/product,你有.get .post .delete(等)在1个api路线

    Clean 解决方案 (/api/product.js)

    const handler = async (req, res) => {
       
       try {
    
       }
    
       catch(e){
       
       }
    }
    

    【讨论】:

    • 没有这个模块可以做到吗?
    • 不确定,但如果您喜欢不使用任何模块,则需要为 API 编写模式和处理程序。
    猜你喜欢
    • 1970-01-01
    • 2018-06-05
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2012-05-08
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多