A Koa Response object is an abstraction on top of node’s vanilla response object, providing additional functionality that is useful for everyday HTTP server development. The Koa response object is embedded in the context object, this. Let’s log out the response object whenever we get a request.
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); _.get('/hello', getMessage); function *getMessage(){ this.body = 'Your request has been logged.'; console.log(this.response); } app.use(_.routes()); app.listen(3000);
When you run this code and navigate to https://localhost:3000/hello then you’ll receive the following response.
On your console, you’ll get the request object logged out.
{ status: 200, message: 'OK', header: { 'content-type': 'text/plain; charset=utf-8', 'content-length': '12' }, body: 'Your request has been logged.' }
The status and message are automatically set by Koa but can be modified by us. If we don’t set the response body, the status code is set to 404. Once we set the response body, the status is set to 200 by default. We can explicitly override this behavior.
We have access to many useful properties of the response using this object. Let us look at some examples −
response.header
Provides all the response headers.
response.status
Provides the response status (200, 404, 500, etc). This property is also used to set the response status.
response.message
Provides the response message. This property is also used to set custom messages with responses. It is associated with response.status.
response.body
Get or set the response body. Usually, we access it using the context object. This is just another way to access it. The body could be of the type: String, Buffer, Stream, Object or Null.
response.type
Get or set the content type of the current response.
response.get(field)
This function is used to get the values of headers with case insensitive value field.
response.set(field, value)
This function is used to set a header on the response using field and value pair.
response.remove(field)
This function is used to unset a header on the response using a field name.
You can read more about the response object in the docs at Response.
Next Topic:-Click Here
Pingback: Koa.js - Request Object - Adglob Infosystem Pvt Ltd
Thanks for sharing, this is a fantastic blog post.Thanks Again. Fantastic.