【问题标题】:Multiple methods on the same route in ExpressExpress中同一条路线上的多种方法
【发布时间】:2015-11-13 08:47:29
【问题描述】:

我正在处理的 API 中有 3 种不同的方法响应,当前设置如下:

app.use('/image', require('./routes/image/get'));
app.post('/image', require('./routes/image/post'));
app.put('/image', require('./routes/image/put'));

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: express


    【解决方案1】:

    您可以在您的appExpress 对象上使用.route(),以减少路由定义中的一些冗余。

    app.route('/image')
         .post(require('./routes/image/post'))
         .put(require('./routes/image/put'));
    

    还有.all(),无论请求http方法如何,都会调用你的处理程序。

    没有use()

    我省略了上面提到的.use(),因为它在 Route 对象上不可用——它设置了应用程序中间件。路由器是另一层中间件(请参阅this question 了解差异的解释)。如果意图真的是调用.use(),而不是.get(),那么该行必须保留,调用.route()(中间件注册顺序很重要)之前。

    为不同的 http 方法重用相同的处理程序

    如果希望为一组方法重用相同的处理程序,请采用以下样式:

    app.route("/image").allOf(["post", "put"], function (req, res) {
        //req.method can be used to alter handler behavior.
        res.send("/image called with http method: " + req.method);
    });
    

    然后,可以通过向express.Route的原型添加新属性来获得所需的功能:

    var express = require('express');
    
    express.Route.prototype.allOf = function (methods /*, ... */) {
        "use strict";
    
        var i, varargs, methodFunc, route = this;
    
        methods = (typeof methods === "string") ? [methods] : methods;
        if (methods.length < 1) {
            throw new Error("You must specify at least one method name.");
        }
    
        varargs = Array.prototype.slice.call(arguments, 1);
        for (i = 0; i < methods.length; i++) {
            methodFunc = route[methods[i]];
            if (! (methodFunc instanceof Function)) {
                throw new Error("Unrecognized method name: " +
                                methods[i]);
            }
            route = methodFunc.apply(route, varargs);
        }
    
        return route;
    };
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 2016-04-07
      • 2021-08-06
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      相关资源
      最近更新 更多