[英]Extending express.Router
Is there a way to extend express.Router
?有没有办法扩展
express.Router
?
I tried this :我试过这个:
class Test extends express.Routeur() {
};
But express throws me an error.但是快递给我一个错误。
Any solution ?任何解决方案?
The right way to do it:正确的做法:
class Test extends express.Router {
constructor() {
super();
this.get('/', (req, res) => console.log('test'));
}
};
When you write express.Router()
(with parentheses) you already call the constructor and therefore you're trying to extend an object instead of class.当您编写
express.Router()
(带括号)时,您已经调用了构造函数,因此您正在尝试扩展一个对象而不是类。
You can't do that because express.Router
is a function.你不能这样做,因为
express.Router
是一个函数。 I haven't found how to extend a class with the function.我还没有找到如何使用该函数扩展类。 But you can use an approach how this http://brianflove.com/2016/03/29/typescript-express-node-js/ or use standard approach with ES2015:
但是您可以使用一种方法如何http://brianflove.com/2016/03/29/typescript-express-node-js/或使用 ES2015 的标准方法:
import * as express from 'express';
let router = express.Router();
/* GET home page. */
router.get('/', (req, res, next) => {
res.render('index', { title: 'Express' });
});
export = router;
Maybe something like this:也许是这样的:
function My_Router() {
return express.Router.apply(this, arguments);
}
var myRouter = new My_Router();
Excuse me, I don't know English at all.对不起,我根本不懂英语。 Thanks to Google Translate ...
感谢谷歌翻译...
The constructor function should return a perfect (function, in fact) object of a router.构造函数应该返回一个完美的(实际上是函数)路由器对象。 You can add to this object, whatever you want, or change it as you wish.
您可以随心所欲地向该对象添加任何内容,也可以根据需要对其进行更改。 Each interface will have a new router object, of course.
当然,每个接口都会有一个新的路由器对象。
It is also necessary to determine the prototype of the constructor function.还需要确定构造函数的原型。 This happens in line 6.
这发生在第 6 行。
const Router = require("express").Router;
const myRouter = function () {
const router = Router();
Object.setPrototypeOf(Router, myRouter);
router.myGet = function (path) {
router.get.call(this, arguments);
console.log("is my get function!!");
};
return router;
};
const router_custom = new myRouter();
router_custom.myGet("/", (req, res) => {
res.send("hay!!");
});
May be something like this would help可能是这样的事情会有所帮助
class YourController extends express.Router{
constructor(){
super()
this.get("/", (req, res)=>{
//do somthing
res.send("return something");
})
this.get("/:id", (req, res)=>{
//do something
res.send("return something);
})
}
}
module.exports = new YourController();
Use It As :将其用作:
const yourExtendedRouter = require("../controllers/YourController")
router.use("/base-url", yourExtendedRouter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.