首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Koa.js与ES6结合使用

将Koa.js与ES6结合使用
EN

Stack Overflow用户
提问于 2016-05-05 09:29:46
回答 1查看 5.3K关注 0票数 3

我现在正在用Express编写REST。我一直在阅读Koa.js,这听起来很有趣,但我似乎不知道如何用Koa.js编写适当的ES6特性。我正在尝试构建一个结构化的应用程序,这就是我现在所拥有的:

注意:我用的是考拉路线包裹,

代码语言:javascript
复制
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();

它工作,但它看起来和感觉笨重。有更好的方法吗?

EN

回答 1

Stack Overflow用户

发布于 2016-05-12 06:53:30

仅仅因为ES6有类,并不意味着当它们可能不是作业的合适工具时,您绝对必须使用它们。:)

这里有一个例子,说明我通常是怎么做的。请不要说这是的方式,而不是的方式。

代码语言:javascript
复制
// 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的。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37047050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档