模块化快递应用
要使快速 Web 应用程序模块化使用路由器工厂:
模块:
// greet.js
const express = require('express');
module.exports = function(options = {}) { // Router factory
const router = express.Router();
router.get('/greet', (req, res, next) => {
res.end(options.greeting);
});
return router;
};
应用:
// app.js
const express = require('express');
const greetMiddleware = require('./greet.js');
express()
.use('/api/v1/', greetMiddleware({ greeting:'Hello world' }))
.listen(8080);
这将使你的应用程序模块化,可自定义并且你的代码可重用。
访问 http://<hostname>:8080/api/v1/greet
时,输出将为 Hello world
更复杂的例子
显示中间件工厂优势的服务示例。
模块:
// greet.js
const express = require('express');
module.exports = function(options = {}) { // Router factory
const router = express.Router();
// Get controller
const {service} = options;
router.get('/greet', (req, res, next) => {
res.end(
service.createGreeting(req.query.name || 'Stranger')
);
});
return router;
};
应用:
// app.js
const express = require('express');
const greetMiddleware = require('./greet.js');
class GreetingService {
constructor(greeting = 'Hello') {
this.greeting = greeting;
}
createGreeting(name) {
return `${this.greeting}, ${name}!`;
}
}
express()
.use('/api/v1/service1', greetMiddleware({
service: new GreetingService('Hello'),
}))
.use('/api/v1/service2', greetMiddleware({
service: new GreetingService('Hi'),
}))
.listen(8080);
当访问 http://<hostname>:8080/api/v1/service1/greet?name=World
时,输出将是 Hello, World
并且访问 http://<hostname>:8080/api/v1/service2/greet?name=World
,输出将是 Hi, World
。