”;
A Koa Request object is an abstraction on top of node”s vanilla request object, providing additional functionality that is useful for everyday HTTP server development. The Koa request object is embedded in the context object, this. Let’s log out the request 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(){ console.log(this.request); this.body = ''Your request has been logged.''; } app.use(_.routes()); app.listen(3000);
When you run this code and navigate to https://localhost:3000/hello, then you will receive the following response.
On your console, you”ll get the request object logged out.
{ method: ''GET'', url: ''/hello/'', header: { host: ''localhost:3000'', connection: ''keep-alive'', ''upgrade-insecure-requests'': ''1'', ''user-agent'': ''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'', accept: ''text/html,application/xhtml+xml, application/xml;q = 0.9,image/webp,*/*;q = 0.8'', dnt: ''1'', ''accept-encoding'': ''gzip, deflate, sdch'', ''accept-language'': ''en-US,en;q = 0.8'' } }
We have access to many useful properties of the request using this object. Let us look at some examples.
request.header
Provides all the request headers.
request.method
Provides the request method(GET, POST, etc.)
request.href
Provides the full request URL.
request.path
Provides the path of the request. Without query string and base url.
request.query
Gives the parsed query string. For example, if we log this on a request such as https://localhost:3000/hello/?name=Ayush&age=20&country=India, then we”ll get the following object.
{ name: ''Ayush'', age: ''20'', country: ''India'' }
request.accepts(type)
This function returns true or false based on whether the requested resources accept the given request type.
You can read more about the request object in the docs at Request.
”;