我现在正在用Express编写REST。我一直在阅读Koa.js,这听起来很有趣,但我似乎不知道如何用Koa.js编写适当的ES6特性。我正在尝试构建一个结构化的应用程序,这就是我现在所拥有的:
注意:我用的是考拉路线包裹,
let koa = require('koa');
let route = require('koa-route');
let app = koa();
class Routes {
example() {
return function* () {
this.body = 'hello world';
}
}
}
class Server {
constructor(port) {
this.port = port;
}
addGetRequest(url, func) {
app.use(route.get('/', func());
}
listen() {
app.listen(this.port);
}
}
const port = 8008;
let routes = new Routes();
let server = new Server(port);
server.addGetRequest('/', routes.example);
server.listen();它工作,但它看起来和感觉笨重。有更好的方法吗?
发布于 2016-05-12 06:53:30
仅仅因为ES6有类,并不意味着当它们可能不是作业的合适工具时,您绝对必须使用它们。:)
这里有一个例子,说明我通常是怎么做的。请不要说这是是的方式,而不是的的方式。
// api/exampleApi.js
const controller = {
getExample: (ctx) => {
ctx.body = { message: 'Hello world' };
}
}
export default function (router) {
router.get('/example', controller.getExample);
}
// server.js
import Koa from 'koa';
import KoaRouter from 'koa-router';
import exampleApi from 'api/exampleApi';
const app = new Koa();
const router = new KoaRouter();
exampleApi(router);
app.use(router.routes());
app.listen(process.env.PORT || 3000);请注意:这个例子是基于Koa 2和Koa路由器7的。
https://stackoverflow.com/questions/37047050
复制相似问题