Koa.js - serving static files and REST API

前端 未结 3 2029
名媛妹妹
名媛妹妹 2021-02-09 02:50

I\'m new to koa.js library and I need some help. I\'m trying to make simple REST application using koa. I have a static html and javascript files I want to serve on route

3条回答
  •  执笔经年
    2021-02-09 03:10

    It was a little hard for me to follow what you were doing in your example code... Here is a simple example that does everything your wanting:

    'use strict';
    let koa     = require('koa'),
        send    = require('koa-send'),
        router  = require('koa-router')(),
        serve   = require('koa-static');
    
    let app = koa();
    // serve files in public folder (css, js etc)
    app.use(serve(__dirname + '/public'));
    
    // rest endpoints
    router.get('/api/whatever', function *(){
      this.body = 'hi from get';
    });
    router.post('/api/whatever', function *(){
      this.body = 'hi from post'
    });
    
    app.use(router.routes());
    
    // this last middleware catches any request that isn't handled by
    // koa-static or koa-router, ie your index.html in your example
    app.use(function* index() {
      yield send(this, __dirname + '/index.html');
    });
    
    app.listen(4000);
    

提交回复
热议问题