ctx.request.accepts()
Checks the `Accept` request header and returns the best matching content type from the given candidates.
Syntax
ctx.request.accepts(...types) // or ctx.accepts(...types) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
types | ...string | Yes | One or more MIME types or file extensions to negotiate. Evaluated in order of the client's quality preference. |
Returns
string | false — The best matching type, or `false` when no types are acceptable.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
const accepted = ctx.request.accepts('json', 'html', 'text');
if (accepted === 'json') {
ctx.body = { data: 'example' };
} else if (accepted === 'html') {
ctx.type = 'html';
ctx.body = '<p>example</p>';
} else {
ctx.throw(406);
}
});
app.listen(3000);
Output
curl -H 'Accept: text/html' localhost:3000
<p>example</p>
Notes
`ctx.accepts()` on the context object is an alias for
`ctx.request.accepts()`. Uses the [accepts](https://github.com/jshttp/accepts)
library. Related: `ctx.acceptsCharsets()`, `ctx.acceptsEncodings()`,
`ctx.acceptsLanguages()`.