Table of Contents for
Server Side development with Node.js and Koa.js Quick Start Guide

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Server Side development with Node.js and Koa.js Quick Start Guide by Olayinka Omole Published by Packt Publishing, 2018
  1. Server Side Development with Node.js and Koa.js Quick Start Guide
  2. Title Page
  3. Copyright and Credits
  4. Server Side Development with Node.js and Koa.js Quick Start Guide
  5. About Packt
  6. Why subscribe?
  7. Packt.com
  8. Contributors
  9. About the author
  10. About the reviewer
  11. Packt is searching for authors like you
  12. Table of Contents
  13. Preface
  14. Who this book is for
  15. What this book covers
  16. To get the most out of this book
  17. Download the example code files
  18. Download the color images
  19. Code in action
  20. Conventions used
  21. Get in touch
  22. Reviews
  23. Introducing Koa
  24. Technical requirements
  25. What is Koa?
  26. What can you do with Koa?
  27. Why choose Koa?
  28. When you should not use Koa
  29. Koa versus Express
  30. How can this book help you understand Koa better?
  31. Summary
  32. Getting Started with Koa
  33. Technical requirements
  34. Modern JavaScript
  35. A primer on Node
  36. What is async… await?
  37. The promise class
  38. Introducing async
  39. Introducing await
  40. Installing Koa
  41. Using Babel
  42. Starting a server in Koa
  43. Summary
  44. Koa Core Concepts
  45. Technical requirements
  46. The application object
  47. Useful application methods
  48. Settings
  49. The context object
  50. Context object API
  51. Aliases
  52. The request object
  53. Content negotiation
  54. The response object
  55. Middleware
  56. Cascading in Koa
  57. Defining middleware
  58. Registering middleware
  59. Common middleware
  60. Summary
  61. Handling Errors in Koa
  62. Technical requirements
  63. Catching errors in Koa
  64. Koa's default error handler
  65. Emitting errors
  66. Error event listener
  67. Throwing HTTP errors
  68. Writing error handlers
  69. Summary
  70. Building an API in Koa
  71. Technical requirements
  72. Project setup
  73. Initialization
  74. Installing dependencies
  75. Structure
  76. Building the application
  77. Starting the server
  78. Using Nodemon
  79. Connecting to a database
  80. Creating data models
  81. Setting up the router
  82. Setting up a logger
  83. Creating contact endpoints and controller actions
  84. Retrieving all contacts
  85. Storing new contacts
  86. Retrieving a single contact
  87. Updating a contact
  88. Deleting a contact
  89. Validating requests
  90. Useful notes
  91. Summary
  92. Building an Application in Koa
  93. Technical requirements
  94. About the application
  95. Setting up a project
  96. Installing dependencies
  97. Project structure
  98. Building the application
  99. Starting the server
  100. Connecting to the database
  101. Creating data models
  102. The user model
  103. The post model
  104. Setting up the router
  105. Setting up the views
  106. Using partials
  107. Setting up sessions
  108. Handling authentication
  109. User registration and login
  110. Authentication middleware
  111. Creating controller functions
  112. Summary
  113. Other Books You May Enjoy
  114. Leave a review - let other readers know what you think

The request object

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

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&param2=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 protocolhttp or httpsThis 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'