2013-11-13 17:01:15 +00:00
# Response
A Koa `Response` object is an abstraction on top of node's vanilla response object,
providing additional functionality that is useful for every day HTTP server
development.
## API
2014-09-25 11:36:23 +00:00
### response.header
2013-11-13 17:01:15 +00:00
2014-01-17 08:30:35 +00:00
Response header object.
2015-04-23 09:28:02 +00:00
### response.headers
Response header object. Alias as `response.header` .
2014-09-25 11:36:23 +00:00
### response.socket
2014-02-01 02:39:47 +00:00
2014-01-17 08:30:35 +00:00
Request socket.
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.status
2013-11-13 17:01:15 +00:00
2017-02-18 21:57:45 +00:00
Get response status. By default, `response.status` is set to `404` unlike node's `res.statusCode` which defaults to `200` .
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.status=
2013-11-13 17:01:15 +00:00
2014-06-13 07:30:59 +00:00
Set response status via numeric code:
2013-11-13 17:01:15 +00:00
- 100 "continue"
- 101 "switching protocols"
- 102 "processing"
- 200 "ok"
- 201 "created"
- 202 "accepted"
- 203 "non-authoritative information"
- 204 "no content"
- 205 "reset content"
- 206 "partial content"
- 207 "multi-status"
2017-04-21 07:50:39 +00:00
- 208 "already reported"
- 226 "im used"
2013-11-13 17:01:15 +00:00
- 300 "multiple choices"
- 301 "moved permanently"
2017-04-21 07:50:39 +00:00
- 302 "found"
2013-11-13 17:01:15 +00:00
- 303 "see other"
- 304 "not modified"
- 305 "use proxy"
- 307 "temporary redirect"
2017-04-21 07:50:39 +00:00
- 308 "permanent redirect"
2013-11-13 17:01:15 +00:00
- 400 "bad request"
- 401 "unauthorized"
- 402 "payment required"
- 403 "forbidden"
- 404 "not found"
- 405 "method not allowed"
- 406 "not acceptable"
- 407 "proxy authentication required"
2017-04-21 07:50:39 +00:00
- 408 "request timeout"
2013-11-13 17:01:15 +00:00
- 409 "conflict"
- 410 "gone"
- 411 "length required"
- 412 "precondition failed"
2017-04-21 07:50:39 +00:00
- 413 "payload too large"
- 414 "uri too long"
2013-11-13 17:01:15 +00:00
- 415 "unsupported media type"
2017-04-21 07:50:39 +00:00
- 416 "range not satisfiable"
2013-11-13 17:01:15 +00:00
- 417 "expectation failed"
2017-07-19 18:04:59 +00:00
- 418 "I'm a teapot"
2013-11-13 17:01:15 +00:00
- 422 "unprocessable entity"
- 423 "locked"
- 424 "failed dependency"
- 426 "upgrade required"
- 428 "precondition required"
- 429 "too many requests"
- 431 "request header fields too large"
- 500 "internal server error"
- 501 "not implemented"
- 502 "bad gateway"
- 503 "service unavailable"
2017-04-21 07:50:39 +00:00
- 504 "gateway timeout"
2013-11-13 17:01:15 +00:00
- 505 "http version not supported"
- 506 "variant also negotiates"
- 507 "insufficient storage"
2017-04-21 07:50:39 +00:00
- 508 "loop detected"
2013-11-13 17:01:15 +00:00
- 510 "not extended"
- 511 "network authentication required"
2013-12-19 07:48:45 +00:00
__NOTE__: don't worry too much about memorizing these strings,
if you have a typo an error will be thrown, displaying this list
so you can make a correction.
2013-11-13 17:01:15 +00:00
2014-10-01 12:12:20 +00:00
### response.message
Get response status message. By default, `response.message` is
associated with `response.status` .
### response.message=
Set response status message to the given value.
2014-09-25 11:36:23 +00:00
### response.length=
2013-11-13 17:01:15 +00:00
Set response Content-Length to the given value.
2014-09-25 11:36:23 +00:00
### response.length
2013-11-13 17:01:15 +00:00
Return response Content-Length as a number when present, or deduce
2016-03-22 18:03:10 +00:00
from `ctx.body` when possible, or `undefined` .
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.body
2013-11-13 17:01:15 +00:00
2014-01-04 10:05:05 +00:00
Get response body.
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.body=
2013-11-13 17:01:15 +00:00
Set response body to one of the following:
- `string` written
- `Buffer` written
- `Stream` piped
2017-04-23 23:17:48 +00:00
- `Object` || `Array` json-stringified
2013-11-13 17:01:15 +00:00
- `null` no content response
2014-10-01 12:12:20 +00:00
If `response.status` has not been set, Koa will automatically set the status to `200` or `204` .
2014-01-04 10:05:05 +00:00
2018-12-12 04:33:36 +00:00
Koa doesn't guard against everything that could be put as a response body -- a function doesn't serialise meaningfully, returning a boolean may make sense based on your application, and while an error works, it may not work as intended as some properties of an error are not enumerable. We recommend adding middleware in your app that asserts body types per app. A sample middleware might be:
```
app.use(async (ctx, next) => {
await next()
ctx.assert.equal('object', typeof ctx, 500, 'some dev did something wrong')
})
```
2013-11-13 17:01:15 +00:00
#### String
The Content-Type is defaulted to text/html or text/plain, both with
a default charset of utf-8. The Content-Length field is also set.
#### Buffer
The Content-Type is defaulted to application/octet-stream, and Content-Length
is also set.
#### Stream
The Content-Type is defaulted to application/octet-stream.
2016-02-29 00:18:14 +00:00
Whenever a stream is set as the response body, `.onerror` is automatically added as a listener to the `error` event to catch any errors.
In addition, whenever the request is closed (even prematurely), the stream is destroyed.
If you do not want these two features, do not set the stream as the body directly.
For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.
See: https://github.com/koajs/koa/pull/612 for more information.
Here's an example of stream error handling without automatically destroying the stream:
```js
2016-03-15 15:35:52 +00:00
const PassThrough = require('stream').PassThrough;
2016-02-29 00:18:14 +00:00
2017-07-21 01:01:03 +00:00
app.use(async ctx => {
2016-03-22 18:03:10 +00:00
ctx.body = someHTTPStream.on('error', ctx.onerror).pipe(PassThrough());
2016-03-15 15:35:52 +00:00
});
2016-02-29 00:18:14 +00:00
```
2013-11-13 17:01:15 +00:00
#### Object
2017-04-23 23:17:48 +00:00
The Content-Type is defaulted to application/json. This includes plain objects `{ foo: 'bar' }` and arrays `['foo', 'bar']` .
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.get(field)
2013-11-13 17:01:15 +00:00
Get a response header field value with case-insensitive `field` .
```js
2017-07-13 17:52:07 +00:00
const etag = ctx.response.get('ETag');
2013-11-13 17:01:15 +00:00
```
2014-09-25 11:36:23 +00:00
### response.set(field, value)
2013-11-13 17:01:15 +00:00
Set response header `field` to `value` :
```js
2016-03-22 18:03:10 +00:00
ctx.set('Cache-Control', 'no-cache');
2013-11-13 17:01:15 +00:00
```
2015-01-25 17:53:55 +00:00
### response.append(field, value)
Append additional header `field` with value `val` .
```js
2016-03-22 18:03:10 +00:00
ctx.append('Link', '< http: / / 127 . 0 . 0 . 1 / > ');
2015-01-25 17:53:55 +00:00
```
2014-09-25 11:36:23 +00:00
### response.set(fields)
2013-11-13 17:01:15 +00:00
Set several response header `fields` with an object:
```js
2016-03-22 18:03:10 +00:00
ctx.set({
2013-11-13 17:01:15 +00:00
'Etag': '1234',
'Last-Modified': date
});
```
2018-12-07 07:24:51 +00:00
This delegates to [setHeader ](https://nodejs.org/dist/latest/docs/api/http.html#http_request_setheader_name_value ) which sets or updates headers by specified keys and doesn't reset the entire header.
2014-12-04 22:22:23 +00:00
### response.remove(field)
2013-11-24 13:06:35 +00:00
Remove header `field` .
2014-09-25 11:36:23 +00:00
### response.type
2013-11-13 17:01:15 +00:00
Get response `Content-Type` void of parameters such as "charset".
```js
2016-03-22 18:03:10 +00:00
const ct = ctx.type;
2013-11-13 17:01:15 +00:00
// => "image/png"
2013-11-20 06:40:52 +00:00
```
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.type=
2013-11-13 17:01:15 +00:00
Set response `Content-Type` via mime string or file extension.
```js
2016-03-22 18:03:10 +00:00
ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';
2013-11-13 17:01:15 +00:00
```
Note: when appropriate a `charset` is selected for you, for
2017-06-12 18:37:16 +00:00
example `response.type = 'html'` will default to "utf-8". If you need to overwrite `charset` ,
use `ctx.set('Content-Type', 'text/html')` to set response header field to value directly.
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.is(types...)
2014-06-13 07:30:59 +00:00
2016-03-22 18:03:10 +00:00
Very similar to `ctx.request.is()` .
2014-06-13 07:30:59 +00:00
Check whether the response type is one of the supplied types.
This is particularly useful for creating middleware that
2014-06-13 16:02:06 +00:00
manipulate responses.
2014-06-13 07:30:59 +00:00
For example, this is a middleware that minifies
2014-06-13 16:02:06 +00:00
all HTML responses except for streams.
2014-06-13 07:30:59 +00:00
```js
2015-10-24 09:21:47 +00:00
const minify = require('html-minifier');
2014-06-13 07:30:59 +00:00
2017-07-21 01:01:03 +00:00
app.use(async (ctx, next) => {
await next();
2014-06-13 07:30:59 +00:00
2016-03-22 18:03:10 +00:00
if (!ctx.response.is('html')) return;
2014-06-13 07:30:59 +00:00
2016-03-22 18:03:10 +00:00
let body = ctx.body;
2014-06-13 16:02:06 +00:00
if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString();
2016-03-22 18:03:10 +00:00
ctx.body = minify(body);
2014-06-13 07:30:59 +00:00
});
```
2014-09-25 11:36:23 +00:00
### response.redirect(url, [alt])
2013-11-13 17:01:15 +00:00
2013-11-20 06:40:52 +00:00
Perform a [302] redirect to `url` .
2013-11-13 17:01:15 +00:00
The string "back" is special-cased
to provide Referrer support, when Referrer
is not present `alt` or "/" is used.
2013-11-20 06:40:52 +00:00
```js
2016-03-22 18:03:10 +00:00
ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');
2013-11-13 17:01:15 +00:00
```
2013-12-19 07:51:51 +00:00
To alter the default status of `302` , simply assign the status
before or after this call. To alter the body, assign it after this call:
2013-11-13 17:01:15 +00:00
```js
2016-03-22 18:03:10 +00:00
ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';
2013-11-13 17:01:15 +00:00
```
2018-10-08 14:43:11 +00:00
### response.attachment([filename], [options])
2013-11-13 17:01:15 +00:00
Set `Content-Disposition` to "attachment" to signal the client
to prompt for download. Optionally specify the `filename` of the
2018-10-08 14:43:11 +00:00
download and some [options ](https://github.com/jshttp/content-disposition#options ).
2013-11-13 17:01:15 +00:00
2014-09-25 11:36:23 +00:00
### response.headerSent
2013-11-13 17:01:15 +00:00
Check if a response header has already been sent. Useful for seeing
if the client may be notified on error.
2014-09-25 11:36:23 +00:00
### response.lastModified
2013-11-20 06:40:52 +00:00
Return the `Last-Modified` header as a `Date` , if it exists.
2014-09-25 11:36:23 +00:00
### response.lastModified=
2013-11-20 06:40:52 +00:00
Set the `Last-Modified` header as an appropriate UTC string.
You can either set it as a `Date` or date string.
```js
2016-03-22 18:03:10 +00:00
ctx.response.lastModified = new Date();
2013-11-20 06:40:52 +00:00
```
2014-09-25 11:36:23 +00:00
### response.etag=
2013-11-20 06:40:52 +00:00
Set the ETag of a response including the wrapped `"` s.
2014-09-25 11:36:23 +00:00
Note that there is no corresponding `response.etag` getter.
2013-11-20 06:40:52 +00:00
```js
2016-03-22 18:03:10 +00:00
ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
2013-12-19 07:48:45 +00:00
```
2014-01-17 08:30:35 +00:00
2014-09-25 11:36:23 +00:00
### response.vary(field)
2014-02-01 02:39:47 +00:00
2014-01-17 08:30:35 +00:00
Vary on `field` .
2016-03-04 03:57:52 +00:00
### response.flushHeaders()
Flush any set headers, and begin the body.