Koa.js – Overview

Koa.js – Overview ”; Previous Next A web application framework provides you with a simple API to build websites, web apps, and backends. You need not worry about low level protocols, processes, etc. What is Koa? Koa provides a minimal interface to build applications. It is a very small framework (600 LoC) which provides the required tools to build apps and is quite flexible. There are numerous modules available on npm for Koa, which can be directly plugged into it. Koa can be thought of as the core of express.js without all the bells and whistles. Why Koa? Koa has a small footprint (600 LoC) and is a very thin layer of abstraction over the node to create server side apps. It is completely pluggable and has a huge community. This also allows us to easily extend Koa and use it according to our needs. It is built using the bleeding edge technology (ES6) which gives it an edge over older frameworks such as express. Pug Pug (earlier known as Jade) is a terse language for writing HTML templates. Produces HTML Supports dynamic code Supports reusability (DRY) It is one of the most popular templating language used with Koa. MongoDB and Mongoose MongoDB is an open-source, document database designed for ease of development and scaling. We”ll use this database to store data. Mongoose is a client API for node.js which makes it easy to access our database from our Koa application. Print Page Previous Next Advertisements ”;

Koa.js – Static Files

Koa.js – Static Files ”; Previous Next Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default doesn”t allow you to serve static files. We need a middleware to serve this purpose. Go ahead and install koa-serve − $ npm install –save koa-static Now we need to use this middleware. Before that create a directory called public. We will store all our static files here. This allows us to keep our server code secure as nothing above this public folder would be accessible to the clients. After you”ve created a public directory, create a file named hello.txt in it with any content you like. Now add the following to your app.js. var serve = require(”koa-static”); var koa = require(”koa”); var app = koa(); app.use(serve(”./public”)); app.listen(3000); Note − Koa looks up the files relative to the static directory, so the name of the static directory is not part of the URL. The root route is now set to your public dir, so all static files you load will be considering public as the root. To test that this is working fine, run your app and visit https://localhost:3000/hello.txt You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file. Multiple Static Dirs We can also set multiple static assets directories using − var serve = require(”koa-static”); var koa = require(”koa”); var app = koa(); app.use(serve(”./public”)); app.use(serve(”./images”)); app.listen(3000); Now when we request a file, Koa will search these directories and send us the matching file. Print Page Previous Next Advertisements ”;

Koa.js – Sessions

Koa.js – Sessions ”; Previous Next HTTP is stateless, hence in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. However, they are both readable on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID. We”ll need the koa-session, thus install it using − npm install –save koa-session We will put the koa-session middleware in place. In this example, we”ll use the RAM to store sessions. Never use this in production environments. The session middleware handles everything, i.e. creating the session, setting the session cookie, and creating the session object in context object. Whenever we make a request from the same client again, we will have their session information stored with us (given that server was not restarted). We can add more properties to this session object. In the following example, we will create a view counter for a client. var session = require(”koa-session”); var koa = require(”koa”); var app = koa(); app.keys = [”Shh, its a secret!”]; app.use(session(app)); // Include the session middleware app.use(function *(){ var n = this.session.views || 0; this.session.views = ++n; if(n === 1) this.body = ”Welcome here for the first time!”; else this.body = “You”ve visited this page ” + n + ” times!”; }) app.listen(3000); What the above code does is, when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the user visits, the cookie is checked and the page_view session variable is updated accordingly. Now if you run the app and go to localhost:3000, you”ll get the following response. If you revisit the page, the page counter will increase. In this case, the page was refreshed 12 times. Print Page Previous Next Advertisements ”;

Koa.js – Hello World

Koa.js – Hello World ”; Previous Next Once we have set up the development, it is time to start developing our first app using Koa. Create a new file called app.js and type the following in it. var koa = require(”koa”); var app = new koa(); app.use(function* (){ this.body = ”Hello world!”; }); app.listen(3000, function(){ console.log(”Server running on https://localhost:3000”) }); Save the file, go to your terminal and type. $ nodemon app.js This will start the server. To test this app, open your browser and go to https://localhost:3000 and you should receive the following message. How This App Works? The first line imports Koa in our file. We have access to its API through the variable Koa. We use it to create an application and assign it to var app. app.use(function) − This function is a middleware, which gets called whenever our server gets a request. We”ll learn more about middleware in the subsequent chapters. The callback function is a generator, which we”ll see in the next chapter. The context of this generator is called context in Koa. This context is used to access and modify the request and response objects. We are setting the body of this response to be Hello world!. app.listen(port, function) − This function binds and listens for connections on the specified port. Port is the only required parameter here. The callback function is executed, if the app runs successfully. Print Page Previous Next Advertisements ”;

Koa.js – File Uploading

Koa.js – File Uploading ”; Previous Next Web applications need to provide the functionality to allow file uploads. Let us see how we can receive files from the clients and store them on our server. We have already used the koa-body middleware for parsing requests. This middleware is also used for handling file uploads. Let us create a form that allows us to upload files and then save these files using Koa. First create a template named file_upload.pug with the following contents. html head title File uploads body form(action = “/upload” method = “POST” enctype = “multipart/form-data”) div input(type = “text” name = “name” placeholder = “Name”) div input(type = “file” name = “image”) div input(type = “submit”) Note that you need to give the same encoding type as above in your form. Now let us handle this data on our server. var koa = require(”koa”); var router = require(”koa-router”); var bodyParser = require(”koa-body”); var app = koa(); //Set up Pug var Pug = require(”koa-pug”); var pug = new Pug({ viewPath: ”./views”, basedir: ”./views”, app: app }); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: ”./uploads”}, //This is where the files would come multipart: true, urlencoded: true })); var _ = router(); //Instantiate the router _.get(”/files”, renderForm); _.post(”/upload”, handleForm); function * renderForm(){ this.render(”file_upload”); } function *handleForm(){ console.log(“Files: “, this.request.body.files); console.log(“Fields: “, this.request.body.fields); this.body = “Received your data!”; //This is where the parsed request is stored } app.use(_.routes()); app.listen(3000); When you run this, you get the following form. When you submit this, your console will produce the following output. The files that were uploaded are stored in the path in the above output. You can access the files in the request using this.request.body.files and the fields in that request by this.request.body.fields. Print Page Previous Next Advertisements ”;

Koa.js – URL Building

Koa.js – URL Building ”; Previous Next We can now define routes; they are either static or fixed. To use dynamic routes, we need to provide different types of routes. Using dynamic routes allow us to pass parameters and process based on them. Following is an example of a dynamic route. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); _.get(”/:id”, sendID); function *sendID() { this.body = ”The id you specified is ” + this.params.id; } app.use(_.routes()); app.listen(3000); To test this go to https://localhost:3000/123. You will get the following response. You can replace ”123” in the URL with anything else and it”ll be reflected in the response. Following is a complex example of the above. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); _.get(”/things/:name/:id”, sendIdAndName); function *sendIdAndName(){ this.body = ”id: ” + this.params.id + ” and name: ” + this.params.name; }; app.use(_.routes()); app.listen(3000); To test this go to https://localhost:3000/things/tutorialspoint/12345. You can use the this.params object to access all the parameters you pass in the URL. Note that the above two have different paths. They will never overlap. Also if you want to execute the code when you get ”/things”, then you need to define it separately. Pattern Matched Routes You can also use regex to restrict URL parameter matching. Let”s say you need the id to be five digits long number. You can use the following route definition. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); _.get(”/things/:id([0-9]{5})”, sendID); function *sendID(){ this.body = ”id: ” + this.params.id; } app.use(_.routes()); app.listen(3000); Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you”ll get a Not found message as response. For example, if we define the same routes as above, on requesting with a valid URL, we get − Print Page Previous Next Advertisements ”;

Koa.js – Cascading

Koa.js – Cascading ”; Previous Next Middleware functions are functions that have access to the context object and the next middleware function in the application’s request-response cycle. These functions are used to modify the request and response objects for tasks such as parsing request bodies, adding response headers, etc. Koa goes a step further by yielding ”downstream”, then flowing the control back ”upstream”. This effect is called cascading. Following is a simple example of a middleware function in action. var koa = require(”koa”); var app = koa(); var _ = router(); //Simple request time logger app.use(function* (next) { console.log(“A new request received at ” + Date.now()); //This function call is very important. It tells that more processing is //required for the current request and is in the next middleware function/route handler. yield next; }); app.listen(3000); The above middleware is called for every request on the server. Thus after every request, we will get the following message in the console. A new request received at 1467267512545 To restrict it to a specific route (and all its subroutes), we just need to create the routes like we did for routing. Actually its these middleware only that handle our request. For example, var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); //Simple request time logger _.get(”/request/*”, function* (next) { console.log(“A new request received at ” + Date.now()); yield next; }); app.use(_.routes()); app.listen(3000); Now whenever you request any subroute of ”/request”, only then it”ll log the time. Order of Middleware Calls One of the most important things about middleware in Koa is that the order in which they are written/included in your file, are the order in which they are executed downstream. As soon as we hit a yield statement in a middleware, it switches to the next middleware in line, till we reach the last. Then again we start moving back up and resuming functions from yield statements. For example, in the following code snippet, the first function executes first till yield, then the second middleware till yield, then the third. As we have no more middleware here, we start moving back up, executing in a reverse order, i.e., third, second, first. This example summarizes how to use middleware the Koa way. var koa = require(”koa”); var app = koa(); //Order of middlewares app.use(first); app.use(second); app.use(third); function *first(next) { console.log(“I”ll be logged first. “); //Now we yield to the next middleware yield next; //We”ll come back here at the end after all other middlewares have ended console.log(“I”ll be logged last. “); }; function *second(next) { console.log(“I”ll be logged second. “); yield next; console.log(“I”ll be logged fifth. “); }; function *third(next) { console.log(“I”ll be logged third. “); yield next; console.log(“I”ll be logged fourth. “); }; app.listen(3000); When we visit ”/” after running this code, on our console we will get − I”ll be logged first. I”ll be logged second. I”ll be logged third. I”ll be logged fourth. I”ll be logged fifth. I”ll be logged last. The following diagram summarizes what is actually happening in the above example. Now that we know how to create our own middleware, let us discuss some of the most commonly used community created middleware. Third Party Middleware A list of third party middleware for express is available here. Following are some of the most commonly used middleware − koa-bodyparser koa-router koa-static koa-compress We”ll discuss multiple middleware in the subsequent chapters. Print Page Previous Next Advertisements ”;

Koa.js – Home

Koa.js Tutorial PDF Version Quick Guide Resources Job Search Discussion Koa.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is an open source framework developed and maintained by the creators of Express.js, the most popular node web framework. Audience This tutorial has been created for those who have basic knowledge of HTML, JavaScript(ES6) and how the client-servers work. After completing this tutorial, you”ll be able to build moderately complex websites and backends for mobile applications. Prerequisites You should have basic knowledge of JavaScript(ES6) and HTML. If you are not acquainted with these, we”ll suggest you to go through their tutorials first. Some knowledge of how HTTP works will be quite helpful (not necessary) for you to understand this tutorial. Having basic knowledge on MongoDB will help you with the Database chapter. Print Page Previous Next Advertisements ”;

Koa.js – Environment

Koa.js – Environment ”; Previous Next To get started with developing using the Koa framework, you need to have Node and npm (node package manager) installed. If you don’t already have these, head over to Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. $ node –version $ npm –version You should receive an output similar to − v5.0.0 3.5.2 Please ensure your node version is above 6.5.0. Now that we have Node and npm set up, let us understand what npm is and how to use it. Node Package Manager (npm) npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS. How to Use npm? There are two ways to install a package using npm − globally and locally. Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following command. $ npm install -g <package-name> Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the −g flag. $ npm install <package-name> Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project. Step 1 − Fire up your terminal/cmd, create a new folder named hello-world and cd into it − Step 2 − Now to create the package.json file using npm, use the following. npm init It’ll ask you for the following information − Just keep pressing enter, and enter your name in the “author name” field. Step 3 − Now we have our package.json file set up, we’ll install Koa. To install Koa and add it in our package.json file, use the following command. $ npm install –save koa To confirm Koa installed correctly, run the following command. $ ls node_modules #(dir node_modules for windows) Tip − The –save flag can be replaced by -S flag. This flag ensures that Koa is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project, we just need to run the command npm install and it’ll find the dependencies in this file and install them for us. This is all we need to start development using the Koa framework. To make our development process a lot easier, we will install a tool from npm, nodemon. What this tool does is, it restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command. $ npm install -g nodemon Now we are all ready to dive into Koa! Print Page Previous Next Advertisements ”;

Koa.js – Routing

Koa.js – Routing ”; Previous Next Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command. npm install –save koa-router Now that we have Koa-router installed, let’s look at a simple GET route example. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); //Instantiate the router _.get(”/hello”, getMessage); // Define routes function *getMessage() { this.body = “Hello world!”; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route “/hello”. Our Koa app executes the callback function attached to this route and sends “Hello World!” as the response. We can also have multiple different methods at the same route. For example, var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); //Instantiate the router _.get(”/hello”, getMessage); _.post(”/hello”, postMessage); function *getMessage() { this.body = “Hello world!”; }; function *postMessage() { this.body = “You just called the post method at ”/hello”!n”; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); To test this request, open your terminal and use cURL to execute the following request curl -X POST “https://localhost:3000/hello” A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following − _.all(”/test”, allMessage); function *allMessage(){ this.body = “All HTTP calls regardless of the verb will get this response”; }; Print Page Previous Next Advertisements ”;