- Koa.js - Resources
- Koa.js - Scaffolding
- Koa.js - Logging
- Koa.js - RESTful APIs
- Koa.js - Database
- Koa.js - Caching
- Koa.js - Compression
- Koa.js - Authentication
- Koa.js - Sessions
- Koa.js - Cookies
- Koa.js - Static Files
- Koa.js - File Uploading
- Koa.js - Form Data
- Koa.js - Templating
- Koa.js - Cascading
- Koa.js - Error Handling
- Koa.js - Redirects
- Koa.js - Response Object
- Koa.js - Request Object
- Koa.js - HTTP Methods
- Koa.js - URL Building
- Koa.js - Routing
- Koa.js - Generators
- Koa.js - Hello World
- Koa.js - Environment
- Koa.js - Overview
- Koa.js - Home
Koa.js Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Koa.js - Request Object
A Koa Request object is an abstraction on top of node s vanilla request object, providing additional functionapty 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.psten(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-apve , upgrade-insecure-requests : 1 , user-agent : Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, pke Gecko) Chrome/52.0.2743.116 Safari/537.36 , accept: text/html,apppcation/xhtml+xml, apppcation/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
. Advertisements