Search code examples
reactjskoakoa2

Serve static files with Koa2


How do I serve static files with Koa2 when someone visitis route? I tried milions of things and I always get not found message. Server has responded with status 404

import 'babel-polyfill'
import co from 'co'
import path from 'path'
import render from 'koa-swig'
import Koa from 'koa'
import Router from 'koa-router'
import serve from 'koa-static'
import convert from 'koa-convert'
import send from 'koa-send'

const app: Koa = new Koa()
const route: Routerr = new Router()

**example 1**

app.use(serve(path.resolve(__dirname + '/public/index.html')))

router.get('/lista', function *() {
  console.log('Hello')
})

**example 2**

app.use(async (ctx) => {
  await send(ctx, '/index.html', { root: '/public' })
})

router.get('/lista', function *() {
  console.log('Hello')
})



app.use(router.routes())
app.use(router.allowedMethods())

Solution

  • I made some simple Koa 2 prototype app a little while ago, and basically just copied examples from the module pages. Unfortunately that means I really can't tell you how it work, but I did get something to work and it looks something like this (Using ES2016):

    const serve = require('koa-static');
    const mount = require('koa-mount');
    const Koa = require('koa');
    
    const static_pages = new Koa();
    static_pages.use(serve('static'));
    
    const app = new Koa();
    app
        .use(mount('/static', static_pages))
    

    This "mounts" /static as the root for all static pages, which are located in the local directory static.