Matej Ukmar
Matej Ukmar

Reputation: 2245

How to change Koa's http status code for non-defined routes

What would be best way to change default http status code and response body if somebody accesses undefined (not set) route on Koa server?

Right now Koa returns 404 status and 'Not Found' text in the body. I would like to change it to 501 (Not implemented) just to prevent collisions when actual existing API's response is 404.

Upvotes: 1

Views: 673

Answers (1)

Puwka
Puwka

Reputation: 650

You can add wildcard route to the end of your koa-router It will looks like that:

router
  .get('/', async ctx => ctx.body = 'existed route')
  .all('/*', async ctx => ctx.status = 501)

app.use(router.routes())

GET request to / will return 'existed route' string. All other routes will return 501 status

Hope it will help

Upvotes: 2

Related Questions