Express中同一路由上的多种方法

时间:2015-11-06 18:42:26

标签: express

我在目前正在设置的API中有3种不同的方法响应:

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

有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

您可以在.route() app对象上使用Express来减少路线定义中的部分冗余。

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;
};