The Koa request object is similar to the request object in Node and Express. It can be described as an abstraction of Node's request object. It provides added functionality with its properties and methods for building out everyday HTTP servers.
The methods and properties it exposes include the following:
- request.header: This returns an object containing the request headers. This is aliased in the context object, and can also be accessed with ctx.header. The following code block shows example usage of how the request.header property can be used to retrieve and log the headers from a request:
// log the request headers
console.log(ctx.header);
// or
console.log(ctx.request.header);
- request.header=: This can be used to set the request header object. This can also be accessed with the ctx.header= alias. In the following code block, we create a middleware to set the request header before passing control to the next middleware:
// set request header
app.use(async (ctx, next) => {
const header = {
'accept-encoding': 'gzip'
// .. other header values
};
ctx.request.header = header;
await next();
});
// send response back
app.use(async ctx => {
console.log(ctx.request.header)
ctx.body = 'Hello World';
});
- request.headers: This is used to access the request header object. It is an alias of the request.header property. It can be used in a similar manner to the request.header property as seen here:
console.log(ctx.request.headers);
// => { host: 'localhost:1234',
// 'user-agent': 'curl/7.54.0',
// accept: '*/*' }
- request.headers=: This is used to set the request header object. It is an alias of the request.header= method. It can also be used to set request headers as seen here:
ctx.request.headers = {
'accept-encoding': 'gzip'
};
- request.method: This is used to access the request method. This is particularly useful for situations where you need to decide on whether to carry out an action based on the HTTP method used. An example can be seen in the code block here:
app.use(async ctx => {
const { method } = ctx.request;
if (method === 'POST') {
// carry out validation
}
});
- request.method=: This is used to set the request method. A good use case of this is to implement the popular methodOverrides() middleware. With this, you can modify request methods to fit what you have defined in your application. This is especially useful when you have a client that only supports simple HTTP verbs such as GET and POST. Here is an example of its usage:
// override request method
app.use(async (ctx, next) => {
const { method } = ctx.request.query;
if (method) {
ctx.request.method = method;
}
await next();
});
The preceding example code checks whether a custom method type has been passed in the request query string, then overrides the request to fit the desired method.
- request.length: This returns the request Content-Length as a number, or undefined when the Content-Length is absent. A request with some data in the request body will show how this property works in the example here:
// curl -X POST --data "test data" http://localhost:1234
console.log(ctx.request.length);
// => 9
- request.url: This returns the request URL.
- request.url=: This sets the request URL. The following block can be used for URL rewriting:
// url rewrite middleware
app.use(async (ctx, next) => {
ctx.request.url = '/hello';
await next();
});
- request.originalUrl: This returns the request original URL. For a simple app that implements a rewrite to the /hello route, a visit to the base / route would produce the following results:
// rewrite url
app.use(async (ctx, next) => {
ctx.request.url = '/hello';
await next();
});
app.use(async ctx => {
console.log(ctx.request.url);
// => /hello
console.log(ctx.request.originalUrl);
// => /
ctx.body = 'Hello World';
});
- request.origin: This returns the origin of URL, including the host and protocol. For a local app running on port 1234:
console.log(ctx.request.origin);
// => http://localhost:1234
- request.href: This returns the full request URL with the protocol, host, and url:
console.log(ctx.request.href);
// => http://localhost:1234/?param=1
- request.path: This returns the request pathname. An example request to http://localhost:1234/hello would give the following:
console.log(ctx.request.path);
// => /hello
- request.querystring: This returns the raw query string without the prepending ?.
- request.querystring=: This sets the request raw query string.
- request.search: This returns the request raw query string, along with the prepending ?.
- request.search=: This sets the request raw query string.
- request.host: This returns the request host (hostname:port). It supports the X-Forwarded-Host header when app.proxy is set to true; otherwise, it defaults to the Host header:
console.log(ctx.request.host);
// => localhost:1234
- request.hostname: This returns the request hostname when present. This also supports the X-Forwarded-Host header when app.proxy is set to true. If the host is IPv6, Koa delegates the parsing to the WHATWG URL API (https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_the_whatwg_url_api). Delegating the parsing to the WHATWG URL API may affect performance.
- request.URL: This returns the WHATWG (https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_the_whatwg_url_api) parsed URL object.
- request.type
This returns the value of the Content-Type header, if present, without parameters such as charset:
- request.charset
This returns the request charset if present. Its default value is undefined:
- request.query: This returns the parsed query string from a request. A request to http://localhost:1234/?param1=1¶m2=2 would give the following:
console.log(ctx.request.query);
// => { param1: '1', param2: '2' }
This getter does not support nested object parsing.
- request.query=: This method is used to set the query string to a supplied object:
ctx.query = Object.assign(ctx.query, { param3: 3 });
console.log(ctx.request.query);
// => { param1: '1', param2: '2', param3: '3' }
This setter does not support nested objects.
- request.fresh: This is used to check whether the contents of a request cache have not changed, as shown here:
// check if cache is fresh
if (ctx.request.fresh) {
ctx.status = 304;
return;
}
// cache is stale, return data
ctx.body = "some data";
- request.stale: This is the inverse of the request.fresh method. It checks whether the contents of a request cache have changed.
- request.protocol: This returns the request protocol—http or https. This supports the X-Forwarded-Host header when app.proxy is set to true.
- request.secure: This simply returns a Boolean that is true when the request protocol is https and false when it's http as shown here:
// https://example.com
console.log(ctx.request.secure);
// => true
// http://example.com
console.log(ctx.request.secure);
// => false
- request.ip: This returns the request remote address. This supports X-Forwarded-Host when app.proxy is set to true.
- request.ips: This returns an array of IPs from upstream to downstream, when the X-Forwarded-Host header is set and app.proxy is set to true. It returns an empty array otherwise.
- request.subdomains: This returns the sub-domains on the request as an array. A good illustration of the behavior of this getter can be seen in the Koa docs:
"For example, if the domain is "tobi.ferrets.example.com": If app.subdomainOffset is not set, ctx.subdomains is ["ferrets", "tobi"]. If app.subdomainOffset is 3, ctx.subdomains is ["tobi"]."
- request.is(types...): This checks the value of the Content-Type header and compares it to the values of the types supplied to find a match. If it finds a match, it returns the matching Content-Type. If no request body is not present, it returns null. If no Content-Type is present, or the match fails, then it returns false:
// With Content-Type as text/html
console.log(ctx.is('html'));
// => 'html'
console.log(ctx.is('text/html'));
// => 'text/html'
console.log(ctx.is('text/*', 'text/html'));
// => 'text/html'