您可以在您的app 的Express 对象上使用.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;
};