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

Dev*_*uez 1 express

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

app.use('/image', require('./routes/image/get'));
app.post('/image', require('./routes/image/post'));
app.put('/image', require('./routes/image/put'));
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

ini*_*_js 6

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

app.route('/image')
     .post(require('./routes/image/post'))
     .put(require('./routes/image/put'));
Run Code Online (Sandbox Code Playgroud)

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

use()

我省略了.use()上面提到的 ,因为它在 Route 对象上不可用——它设置了应用程序中间件。路由器是另一层中间件(有关差异的解释,请参阅此问题)。如果意图真的是调用.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);
});
Run Code Online (Sandbox Code Playgroud)

然后,可以通过向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;
};
Run Code Online (Sandbox Code Playgroud)