【问题标题】:Handle POST request from multiple routes all at once一次处理来自多个路由的 POST 请求
【发布时间】:2018-11-19 10:39:26
【问题描述】:

我在我网站的页脚(footer.pug)中提交了一个简单的联系表格:

form(method="POST" action="contact_form")
  input(type='email' name='ct_email' data-name='ct_email' required)
  textarea(type='text' name='ct_message' data-name='ct_message' required)
  button(type='submit') Send

由于表单在模板中,并且整个站点都使用页脚模板,因此可以从各种途径提交表单:

  • /contact_form
  • /route1/contact_form
  • /route1/de/contact_form
  • 等等……

所以现在看来​​我必须为所有可能的路线创建一个处理程序:

router.post('/contact_form', function(req, res, next) {
  // ...
}

router.post('/route1/contact_form', function(req, res, next) {
  // ...
}

如何轻松处理来自所有路由的 POST 请求无需为每个路由编写处理程序

【问题讨论】:

    标签: node.js forms express routing


    【解决方案1】:

    您可以在表单中使用绝对路径引用,即使表单位于不同的页面中,它也会始终提交到相同的路由。

    试试这个

    form(method="POST" action="/contact_form")
    

    请注意,操作已从 contact_form 更改为 /contact_form。当您添加/ 时,您开始将路径引用为域的绝对路径。所以现在,从所有页面,表单将被提交到http://your-domain/contact-form

    【讨论】:

    • 啊,是的!绝对路径就是我要找的,谢谢!
    【解决方案2】:

    不完全确定这是否是您的意思,但 ExpressJS 路由器的第一个参数(我假设这就是 router 在这里所做的)可以是一个数组。所以而不是:

    router.post('/contact_form', function(req, res, next) {
        // ...
    }
    
    router.post('/route1/contact_form', function(req, res, next) {
        // ...
    }
    

    你可以这样做:

    router.post(['/contact_form','route1/contact_form'],function(req,res,next){
        //some fancy logic to handle both routes.
    })
    

    当然,这要求您保留这些可能路线的列表。另一方面,您可以按照 Dinesh Pandiyan 的建议,使用绝对路径。因此,不是 page1.html、page2.html、page3.html 等都有自己的路由器(或路由器阵列中的自己的条目),您实际上是在说“转到域路由,然后转到此地址”。

    【讨论】:

      【解决方案3】:

      每个请求都应该在单独的函数中处理,因为每个请求都有自己的逻辑。但是,如果您愿意

      function request(req, res, next) {
      // Your logic
      }
      
      router.post('/contact_form', request) {
        // ...
      }
      
      router.post('/route1/contact_form', request) {
        // ...
      }
      

      目前,我没有办法测试此代码,但我认为这会对您有所帮助。

      【讨论】:

        【解决方案4】:

        这是另一个潜在的解决方案 - 使用独立函数作为路由处理程序。

        router.post('/a', handlePost);
        router.post('/b', handlePost);
        router.post('/c', handlePost);
        
        function handlePost(req, res, next){
          // use req.path here to figure out what url was called 
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-05
          • 2012-04-02
          • 2015-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多