koa-static going to next middleware

1.1k Views Asked by At

I have a koa 2 server.

The following code are my middlewares:

// parse body
app.use( bodyParser() )

// serve static
app.use( serve( path.join(__dirname, '/public') ) )

// routes
app.use( routes )

// error middleware
app.use( async ctx => ctx.throw(500) )

Everything works well but my problem is that when I go to localhost:8000, where my server lives, in the console I see the following error:

InternalServerError: Internal Server Error at Object.throw (/Users/work/Desktop/server/node_modules/koa/lib/context.js:91:23)

I'm suspecting that after static, the app is going to the next middleware, which is the error middleware.

PS. I'm using app.use( async ctx => ctx.throw(500) ), to call next() if I'm getting errors on the other routes.

Does anyone know how to fix this?

Thanks!

2

There are 2 best solutions below

1
On

use like, you add a middleware to handle your custom error properly...

    // serve static
app.use(serve(path.join(__dirname, '/public')))
// error middleware
app.use(async(ctx, next) => {
    try {
        await next();
    } catch (e) {
        console.log(e.message);
        ctx.body = e.message
    } finally {}
})
// routes
app.use(router.routes()).use(router.allowedMethods());

router.get('/a', ctx => {
    try {
        ctx.body = "sadsa"
    } catch (e) {
        ctx.body = e
        console.log(e);
    } finally {}
});
app.use(ctx => ctx.throw(500))
app.listen(7000)
2
On

I'm suspecting that after static, the app is going to the next middleware, which is the error middleware.

koa-static transfers control to the next middleware by design. Your routes middleware also await to the next middleware. So you get an error.

Does anyone know how to fix this?

It's hard to say what you are going to achieve in the first place. Setting 500 manually is probably a wrong idea. There should be 404 like:

// 404 middleware
app.use(async ({response}, next) => {
  if (!this.body) {
    response.status = 404
    response.body = "Not Found" // or use template   
  }
  await next() // send control flow back (upstream)
})

For SPA (without SSR) you probably want this catch-all route to send APP layout instead. And move that 404 middleware to the beginning of the file (where it will take control on the second "bubbling" phase.

Make sure you checked this