我正在使用 Express 编写 REST API 有一段时间了。我一直在阅读 Koa.js,它听起来很有趣,但我似乎无法弄清楚如何使用 Koa.js 编写正确的 ES6 功能。我正在尝试制作结构化应用程序,这就是我现在拥有的:
注意:我使用的是 koa-route 包,
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();
它可以工作,但看起来和感觉起来都很笨重。有更好的方法吗?
最佳答案
仅仅因为 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 Router 7。
关于javascript - 在 ES6 中使用 Koa.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37047050/