https://github.com/feegloo/koa-default-body
Koa middleware: sets ctx.body = '' (response HTTP 200 instead of 404)
https://github.com/feegloo/koa-default-body
koajs middleware
Last synced: 7 months ago
JSON representation
Koa middleware: sets ctx.body = '' (response HTTP 200 instead of 404)
- Host: GitHub
- URL: https://github.com/feegloo/koa-default-body
- Owner: feegloo
- Created: 2021-01-14T23:45:46.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-03-22T11:54:37.000Z (over 5 years ago)
- Last Synced: 2024-03-26T22:21:30.679Z (over 2 years ago)
- Topics: koajs, middleware
- Language: JavaScript
- Homepage:
- Size: 43.9 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# koa-default-body
Koa middleware which sets `ctx.body = ''` to return `HTTP 200`
By default, if you leave `ctx.body` `undefined`, Koa returns `HTTP 404 Not Found` - this middleware sets `ctx.body = ''` and Koa will return `HTTP 200`
But if you set `ctx.body` or `ctx.status`, this middleware will use it (instead of setting `ctx.body = ''`)
### example
```
import Koa from 'koa'
import Router from 'koa-router'
import defaultBody from 'koa-default-body'
const app = new Koa()
const router = new Router()
router.post('/returns-200-not-404', () => {})
router.get('/return-custom-body-or-status', ctx => {
ctx.body = 'my body my choice'
ctx.status = 403
})
app.use(defaultBody(router))
app.use(router.routes())
app.listen(3000) // pass your port
```
### purpose
It's for reducing boilerplate `ctx.body = ''` at the end of route handler (function with ctx), for undefined routes response is still 404 !
- `ctx.body = ''` is set ONLY for routers registered with `app.use(router.routes())`. When requesting undefined route, like `/foo` - it will still return 404.
### npm package
https://www.npmjs.com/package/koa-default-body