Koa.js – Redirects ”; Previous Next Redirection is very important when creating websites. If a malformed URL is requested or there are some errors on your server, you should redirect them to the respective error pages. Redirects can also be used to keep people out of restricted areas of your website. Let us create an error page and redirect to that page whenever someone requests a malformed URL. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var _ = router(); _.get(”/not_found”, printErrorMessage); _.get(”/hello”, printHelloMessage); app.use(_.routes()); app.use(handle404Errors); function *printErrorMessage() { this.status = 404; this.body = “Sorry we do not have this resource.”; } function *printHelloMessage() { this.status = 200; this.body = “Hey there!”; } function *handle404Errors(next) { if (404 != this.status) return; this.redirect(”/not_found”); } app.listen(3000); When we run this code and navigate to any route other than /hello, we”ll be redirected to /not_found. We have placed the middleware at the end (app.use function call to this middleware). This ensures we reach the middleware at last and send the corresponding response. Following are the results we see when we run the above code. When we navigate to https://localhost:3000/hello, we get − If we navigate to any other route, we get − Print Page Previous Next Advertisements ”;
Category: koajs
Koa.js – Useful Resources
Koa.js – Useful Resources ”; Previous Next The following resources contain additional information on Koa.js. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Development With Vue JS 2 And Spring Boot 54 Lectures 3.5 hours Senol Atac More Detail Node js for Course for beginners + Game project 27 Lectures 2.5 hours Laurence Svekis More Detail Advanced Theoretical JavaScript: Learn Advanced JS Concepts 25 Lectures 2 hours Mehul Mohan More Detail ReactJS Course : Learn React JS From Scratch Best Seller 61 Lectures 4.5 hours Skillbakery More Detail JavaScript Deep Dive: Explore JS (For Beginners-to-Advanced) 129 Lectures 5.5 hours TELCOMA Global More Detail React JS and .NET Core Web API Full Stack Master Course 21 Lectures 3.5 hours Vinay Kumar More Detail Print Page Previous Next Advertisements ”;
Koa.js – Discussion
Discuss Koa.js ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Koa.js – Caching
Koa.js – Caching ”; Previous Next Caching is the term for storing reusable responses in order to make subsequent requests faster. Every browser ships with an implementation of a HTTP cache. All we have to do is ensure that each server response provides correct HTTP header directives to instruct the browser on when and for how long the response can be cached by the browser. Following are some benefits of including caching in your web apps − Your network costs decrease. If your content is cached, you”ll need to send less of it for every subsequent request. Speed and performance of your website increases. Your content can be made available even if your client is offline. We”ll be using the koa-static-cache middleware to implement caching in our app. Install these middleware using − $ npm install –save koa-static-cache Go to your app.js file and add the following code to it. var koa = require(”koa”); var app = koa(); var path = require(”path”); var staticCache = require(”koa-static-cache”); app.use(staticCache(path.join(__dirname, ”public”), { maxAge: 365 * 24 * 60 * 60 //Add these files to caches for a year })) app.listen(3000); The koa-static-cache middleware is used to cache server responses on the client side. The cache-control header is set according to the options we provide while initializing the cache object. We have set the expiration time of this cached response to 1 year. Following are the comparisons of request we have sent before and after the file was cached. Before this file was cached, the returned status code was 200, which is OK. The response headers had multiple information regarding the content to be cached and had also given an ETag for the content. The next time the request was sent, it was sent along with the ETtag. Since our content hadn”t changed on the server, its corresponding ETag also remained the same and the client was told that the copy it has locally is up-to-date with what the server would provide and should use the local one instead of requesting again. Note − For invalidating any cached file, you just need to change its file name and update its reference. This will ensure that you have a new file to send to the client and the client can’t load it back from the cache. Print Page Previous Next Advertisements ”;
Koa.js – RESTful APIs
Koa.js – RESTful APIs ”; Previous Next To create mobile applications, single page applications, use AJAX calls and provide data to clients, you”ll need an API. A popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State). HTTP 1.1 was designed keeping REST principles in mind. REST was introduced by Roy Fielding in 2000 in his paper Fielding Dissertations. RESTful URIs and methods provide us with almost all information we need to process a request. The following table summarizes how the various verbs should be used and how URIs should be named. We”ll be creating a movies API towards the end, so let’s discuss how it”ll be structured. Method URI Details Function GET /movies Safe, cachable Gets the list of all movies and their details GET /movies/1234 Safe, cachable Gets the details of Movie id 1234 POST /movies N/A Creates a new movie with details provided. Response contains the URI for this newly created resource. PUT /movies/1234 Idempotent Modifies movie id 1234 (creates one if it doesn”t already exist). Response contains the URI for this newly created resource. DELETE /movies/1234 Idempotent Movie id 1234 should be deleted, if it exists. Response should contain the status of request. DELETE or PUT /movies Invalid Should be invalid. DELETE and PUT should specify which resource they are working on. Now let’s create this API in Koa. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has loads of other benefits. Replace your index.js file with the following − INDEX.JS var koa = require(”koa”); var router = require(”koa-router”); var bodyParser = require(”koa-body”); var app = koa(); //Set up body parsing middleware app.use(bodyParser({ formidable:{uploadDir: ”./uploads”}, multipart: true, urlencoded: true })); //Require the Router we defined in movies.js var movies = require(”./movies.js”); //Use the Router on the sub route /movies app.use(movies.routes()); app.listen(3000); Now that we have our application set up, let us concentrate on creating the API. First set up the movies.js file. We are not using a database to store the movies but are storing them in memory, so every time the server restarts the movies added by us will vanish. This can easily be mimicked using a database or a file (using node fs module). Import koa-router, create a Router and export it using module.exports. var Router = require(”koa-router”); var router = Router({ prefix: ”/movies” }); //Prefixed all routes with /movies var movies = [ {id: 101, name: “Fight Club”, year: 1999, rating: 8.1}, {id: 102, name: “Inception”, year: 2010, rating: 8.7}, {id: 103, name: “The Dark Knight”, year: 2008, rating: 9}, {id: 104, name: “12 Angry Men”, year: 1957, rating: 8.9} ]; //Routes will go here module.exports = router; GET Routes Define the GET route for getting all the movies. router.get(”/”, sendMovies); function *sendMovies(next){ this.body = movies; yield next; } That”s it. To test out if this is working fine, run your app, then open your terminal and enter − curl -i -H “Accept: application/json” -H “Content-Type: application/json” -X GET localhost:3000/movies You”ll get the following response − [{“id”:101,”name”:”Fight Club”,”year”:1999,”rating”:8.1},{“id”:102,”name”:”Inception”,”year”:2010,”rating”:8.7}, {“id”:103,”name”:”The Dark Knight”,”year”:2008,”rating”:9},{“id”:104,”name”:”12 Angry Men”,”year”:1957,”rating”:8.9}] We have a route to get all the movies. Now let’s create a route to get a specific movie by its id. router.get(”/:id([0-9]{3,})”, sendMovieWithId); function *sendMovieWithId(next){ var ctx = this; var currMovie = movies.filter(function(movie){ if(movie.id == ctx.params.id){ return true; } }); if(currMovie.length == 1){ this.body = currMovie[0]; } else { this.response.status = 404;//Set status to 404 as movie was not found this.body = {message: “Not Found”}; } yield next; } This will get us the movies according to the id that we provide. To test this out, use the following command in your terminal. curl -i -H “Accept: application/json” -H “Content-Type: application/json” -X GET localhost:3000/movies/101 You”ll get the response as − {“id”:101,”name”:”Fight Club”,”year”:1999,”rating”:8.1} If you visit an invalid route, it”ll produce a cannot GET error, while if you visit a valid route with an id that doesn’t exist, it”ll produce a 404 error. We are done with the GET routes. Now, let’s move on to POST route. POST Route Use the following route to handle the POSTed data. router.post(”/”, addNewMovie); function *addNewMovie(next){ //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9].[0-9]$/g)){ this.response.status = 400; this.body = {message: “Bad Request”}; } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: “New movie created.”, location: “/movies/” + newId}; } yield next; } This will create a new movie and store it in the movies variable. To test this route out, enter the following in your terminal − curl -X POST –data “name = Toy%20story&year = 1995&rating = 8.5″ https://localhost:3000/movies You”ll get the following response − {“message”:”New movie created.”,”location”:”/movies/105″} To test if this was added to the movies object, run the get request for /movies/105 again. You”ll get the following response − {“id”:105,”name”:”Toy story”,”year”:”1995″,”rating”:”8.5″} Let’s move on to create the PUT and DELETE routes. PUT Route The PUT route is almost exactly the same as the POST route. We will be specifying the id for the object that”ll be updated/created. Create the route in the following way − router.put(”/:id”, updateMovieWithId); function *updateMovieWithId(next){ //Check if all fields are provided and are valid: if(!this.request.body.name || !this.request.body.year.toString().match(/^[0-9]{4}$/g) || !this.request.body.rating.toString().match(/^[0-9].[0-9]$/g) || !this.params.id.toString().match(/^[0-9]{3,}$/g)){ this.response.status = 400; this.body = {message: “Bad Request”}; } else { //Gets us the index of movie with given id. var updateIndex = movies.map(function(movie){ return movie.id; }).indexOf(parseInt(this.params.id)); if(updateIndex === -1){ //Movie not found, create new movies.push({ id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }); this.body = {message: “New movie created.”, location: “/movies/” + this.params.id}; } else { //Update existing movie movies[updateIndex] = { id: this.params.id, name: this.request.body.name, year: this.request.body.year, rating: this.request.body.rating }; this.body = {message: “Movie id ” + this.params.id + ” updated.”, location: “/movies/” + this.params.id}; } } } This route will do the function we specified in the table above. It”ll update the object with new details if it exists. If it
Koa.js – Cookies
Koa.js – Cookies ”; Previous Next Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps keep track of the users actions. There are numerous uses of HTTP Cookies. Session management Personalization(Recommendation systems) User tracking To use cookies with Koa, we have the functions: ctx.cookies.set() and ctx.cookies.get(). To set a new cookie, let’s define a new route in our Koa app. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); _.get(”/”, setACookie); function *setACookie() { this.cookies.set(”foo”, ”bar”, {httpOnly: false}); } var _ = router(); app.use(_.routes()); app.listen(3000); To check if the cookie is set or not, just go to your browser, fire up the console, and enter − console.log(document.cookie); This will produce the following output (you may have more cookies set maybe due to extensions in your browser). “foo = bar” Here is an example of the above. The browser also sends back cookies every time it queries the server. To view a cookie on your server, on the server console in a route, add the following code to that route. console.log(”Cookies: foo = ”, this.cookies.get(”foo”)); Next time you send a request to this route, you”ll get the following output. Cookies: foo = bar Adding Cookies with Expiration Time You can add cookies that expire. To add a cookie that expires, just pass an object with the property ”expires” set to the time when you want it to expire. For example, var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); _.get(”/”, setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set(”name”, ”value”, { httpOnly: false, expires: 360000 + Date.now() }); } var _ = router(); app.use(_.routes()); app.listen(3000); Deleting Existing Cookies To unset a cookie, simply set the cookie to an empty string. For example, if you need to clear a cookie named foo, use the following code. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); _.get(”/”, setACookie); function *setACookie(){ //Expires after 360000 ms from the time it is set. this.cookies.set(”name”, ””); } var _ = router(); app.use(_.routes()); app.listen(3000); This will unset the said cookie. Note that you should leave the HttpOnly option to be true when not using the cookie in the client side code. Print Page Previous Next Advertisements ”;
Koa.js – Templating
Koa.js – Templating ”; Previous Next Pug is a templating engine. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine, which has a variety of features such as filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this. To use Pug with Koa, we need to install it using the following command. $ npm install –save pug koa-pug Once pug is installed, set it as the templating engine for your app. Add the following code to your app.js file. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var Pug = require(”koa-pug”); var pug = new Pug({ viewPath: ”./views”, basedir: ”./views”, app: app //Equivalent to app.use(pug) }); var _ = router(); //Instantiate the router app.use(_.routes()); //Use the routes defined using the router app.listen(3000); Now, create a new directory called views. Inside the directory, create a file named first_view.pug, and enter the following data in it. doctype html html head title = “Hello Pug” body p.greetings#people Hello Views! To run this page, add the following route to your app. _.get(”/hello”, getMessage); // Define routes function *getMessage(){ this.render(”first_view”); }; You”ll receive the output as − What Pug does is, it converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use ”.” and ”#” to define them. The above code first gets converted to <!DOCTYPE html> <html> <head> <title>Hello Pug</title> </head> <body> <p class = “greetings” id = “people”>Hello Views!</p> </body> </html> Pug is capable of doing much more than simplifying HTML markup. Let’s explore some of these features of Pug. Simple Tags Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. However, the <body> tag was on the same indentation, thus it was a sibling of <head> tag. We don’t need to close tags. As soon as Pug encounters the next tag on the same or the outer indentation level, it closes the tag for us. There are three methods to put text inside of a tag − Space seperated − h1 Welcome to Pug Piped text − div | To insert multiline text, | You can use the pipe operator. Block of text − div. But that gets tedious if you have a lot of text. You can use “.” at the end of tag to denote block of text. To put tags inside this block, simply enter tag in a new line and indent it accordingly. Comments Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to html comments(<!–comment–>). For example, //This is a Pug comment This comment gets converted to − <!–This is a Pug comment–> Attributes To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes, and id for a given html tag. div.container.column.main#division(width = “100”,height = “100”) This line of code, gets converted to − <div class = “container column main” id = “division” width = “100” height = “100”></div> Passing Values to Templates When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following code. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var Pug = require(”koa-pug”); var pug = new Pug({ viewPath: ”./views”, basedir: ”./views”, app: app // equals to pug.use(app) and app.use(pug.middleware) }); var _ = router(); //Instantiate the router _.get(”//dynamic_view”, dynamicMessage); // Define routes function *dynamicMessage(){ this.render(”dynamic”, { name: “TutorialsPoint”, url:”https://www.tutorialspoint.com” }); }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000); Then, create a new view file in the views directory, named dynamic.pug, using the following code. html head title = name body h1 = name a(href = url) URL Open localhost:3000/dynamic in your browser and following should be the output. − We can also use these passed variables within the text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we want to insert Greetings from TutorialsPoint, then we have to use the following code. html head title = name body h1 Greetings from #{name} a(href = url) URL This method of using values is called interpolation. Conditionals We can use conditional statements and looping constructs as well. Consider this practical example, if a user is logged in we would want to display “Hi, User” and if not, then we would want to show him a “Login/Sign Up” link. To achieve this, we can define a simple template such as − html head title Simple template body if(user) h1 Hi, #{user.name} else a(href = “/sign_up”) Sign Up When we render this using our routes, and if we pass an object like − this.render(”/dynamic”,{user: {name: “Ayush”, age: “20”} }); It”ll give a message displaying Hi, Ayush. However, if we don’t pass any object or pass one with no user key, then we will get a Sign up link. Include and Components Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view, we can use an include. Following example shows how we can use an include − Create three views with the following code − header.pug div.header. I”m the header for this website. content.pug html head title Simple template body include ./header.pug h3 I”m the main content include ./footer.pug footer.pug div.footer. I”m the footer for this website. Create a route for this as follows. var koa = require(”koa”); var router = require(”koa-router”); var app = koa(); var Pug = require(”koa-pug”);
Koa.js – Resources
Koa.js – Resources ”; Previous Next Following is a list of resources we have used while developing this tutorial − Koajs.com Koajs – Examples A list of examples created by the community List of official and 3rd party middlewares. A CRUD API using koa.js – A short screencast that goes through creating a CRUD API in Koa.js Koa.js Quickstart screencast Introduction to Koa.js and generators Print Page Previous Next Advertisements ”;
Koa.js – Error Handling
Koa.js – Error Handling ”; Previous Next Error handling plays an important part in building web applications. Koa uses middleware for this purpose as well. In Koa, you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example − var koa = require(”koa”); var app = koa(); //Error handling middleware app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit(”error”, err, this); } }); //Create an error in the next middleware //Set the error message and status code and throw it using context object app.use(function *(next) { //This will set status and message this.throw(”Error Message”, 500); }); app.listen(3000); We have deliberately created an error in the above code and are handling the error in our first middleware”s catch block. This is then emitted to our console as well as sent as the response to our client. Following is the error message we get when we trigger this error. InternalServerError: Error Message at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23) at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13) at next (native) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10) at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63) at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29) at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7) at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5 Right now any request sent to the server will result in this error. Print Page Previous Next Advertisements ”;
Koa.js – Quick Guide
Koa.js – Quick Guide ”; Previous Next Koa.js – Overview 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. Koa.js – Environment 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! Koa.js – Hello World 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