【问题标题】:GET and POST on the same routeGET 和 POST 在同一条路线上
【发布时间】:2018-01-17 18:15:04
【问题描述】:

我正在构建 rest 端点服务器(nodejs 和 restify)。

我需要为两种类型的客户端请求支持相同的路由,一种用于 GET,另一种用于 POST。

目前我通过这种方式解决了它:

server.get('/foo' , _ProcessRequest);
server.post('/foo' , _ProcessRequest);

function _ProcessRequest(req, res , next){...}

但我想知道是否有其他方法可以支持这种类型的请求

谢谢

【问题讨论】:

    标签: node.js post get request restify


    【解决方案1】:

    就个人而言,我发现您的路由结构方式是最干净的,无需使用路由器中间件来抽象出.get().post() 调用。由于您的问题要求其他方式来执行此操作,因此您可以通过其他方式构建 Route 处理程序以实现相同的功能。

    一种构建路由的方法是使用router.route(),然后为每个 HTTP 方法指定一个处理程序。

    server.route('/foo')
      .get(_ProcessRequest)
      .post(_ProcessRequest)
    

    或者,您可以修改 _ProcessRequest 以设置一个条件,使用更中间件样式的处理程序检查 req.method,使用 next() 将不是 GET 或 POST 的请求短路到 /foo

    server.use('/foo', _ProcessRequest)
    
    function _ProcessRequest(req, res, next) {
      // If not either a GET or a POST then continue to next handler
      if (req.method !== 'GET' && req.method !== 'POST') {
        return next() 
      }
    
      // Request is a HTTP GET or POST so perform logic
    }
    

    【讨论】:

    • 感谢您的回复,您能否解释一下为什么您认为在我的情况下不值得使用路由器中间件?我在想它会给我一个更好的灵活性,我错了吗?
    • 第二种解决方案对我不起作用,得到---->AssertionError: handler (function) is required
    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多