ctx.accepts()
Checks whether the request `Accept` header allows one of the given content types and returns the best match.
Syntax
ctx.accepts(...types) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
types | ...string | Yes | One or more MIME types or short extensions (e.g. `"json"`, `"html"`, `"application/xml"`) to negotiate against the `Accept` header. |
Returns
string | false — The best matching type string, or `false` when none match (respond with 406).
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
const type = ctx.accepts('json', 'html');
if (type === 'json') {
ctx.body = { ok: true };
} else if (type === 'html') {
ctx.type = 'html';
ctx.body = '<p>ok</p>';
} else {
ctx.throw(406, 'Not Acceptable');
}
});
app.listen(3000);
Output
curl -H 'Accept: application/json' localhost:3000
{"ok":true}
Notes
Delegates to the [accepts](https://github.com/jshttp/accepts) library.
Also aliased as `ctx.request.accepts()`. Related methods:
`ctx.acceptsEncodings()`, `ctx.acceptsCharsets()`, `ctx.acceptsLanguages()`.