Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I serve static files from a Koa router?

Why in the following case does koa-static fail to work with koa-router?

const Koa = require("koa")
const serve = require("koa-static")
const Router = require("koa-router")

const app = new Koa()
const router = new Router()

// fails with 404... why?
router.use(serve("public"))

// // this, on the other hand, works
// app.use(serve("public"))

app.use(router.middleware())
app.listen(8080)

// browse to "http://localhost:8080/testfile.txt"

I made this GitHub repo to demo the issue: koa-router-static-issue

like image 693
ChaseMoskal Avatar asked Jan 21 '19 08:01

ChaseMoskal


1 Answers

This is essentially how we have stuff configured in our app.

It uses koa-mount to mount the static file server at a particular root URL. If your static file URLs overlap the namespace of your routes, the static files win.

const Koa    = require('koa')
const Router = require('koa-router')
const serve  = require('koa-static')
const mount  = require('koa-mount')

const app    = new Koa()
const router = new Router()

router.get('/public/foobar.txt', (ctx,next) => {

  ctx.body   = "Ta-Da!"
  ctx.status = 200

  return;
})

app.use( mount( '/public', serve('./public') ) ) ;
app.use( router.middleware())

app.listen( 8080 ) ;
like image 77
Nicholas Carey Avatar answered Sep 18 '22 23:09

Nicholas Carey