About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Koa.js

Size: px
Start display at page:

Download "About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Koa.js"

Transcription

1

2 About the Tutorial 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. Copyright & Disclaimer Copyright 2017 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com i

3 Table of Contents About the Tutorial... i Audience... i Prerequisites... i Copyright & Disclaimer... i Table of Contents... ii 1. KOA.JS OVERVIEW... 1 What is Koa?... 1 Why Koa? KOA.JS ENVIRONMENT... 2 Node Package Manager (npm) KOA.JS HELLO WORLD... 4 How This App Works? KOA.JS GENERATORS... 6 Generators in Koa KOA.JS ROUTING KOA.JS URL BUILDING Pattern Matched Routes KOA.JS HTTP METHODS KOA.JS REQUEST OBJECT KOA.JS RESPONSE OBJECT KOA.JS REDIRECTS KOA.JS ERROR HANDLING ii

4 12. KOA.JS CASCADING Order of Middleware Calls KOA.JS TEMPLATING KOA.JS FORM DATA KOA.JS FILE UPLOADING KOA.JS STATIC FILES KOA.JS COOKIES KOA.JS SESSIONS KOA.JS AUTHENTICATION KOA.JS COMPRESSION KOA.JS CACHING KOA.JS DATABASE KOA.JS RESTFUL APIS KOA.JS LOGGING KOA.JS SCAFFOLDING KOA.JS RESOURCES iii

5 1. Koa.js Overview Koa.js 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. 1

6 2. Koa.js Environment Koa.js 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: v Please ensure your node version is above 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: 2

7 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! 3

8 3. Koa.js Hello World Koa.js 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 = koa(); app.use(function* (){ ); this.body = 'Hello world!'; app.listen(3000, function(){ ); console.log('server running on 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 and you should receive the following message. 4

9 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. 5

10 4. Koa.js Generators Koa.js One of the most exciting new features of JavaScript ES6 is a new breed of function, called a generator. Before generators, the whole script was used to usually execute in a top to bottom order, without an easy way to stop code execution and resuming with the same stack later. Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generators allow us to stop code execution in between. Hence, let s take a look at a simple generator. var generator_func = function* (){ ; yield 1; yield 2; var itr = generator_func(); console.log(itr.next()); console.log(itr.next()); console.log(itr.next()); When running the above code, following will be the result. { value: 1, done: false { value: 2, done: false { value: undefined, done: true Let s look inside the above code. We first create a generator called generator_func(). We created an instance of this weird looking function and assigned it to itr. Then we started calling next() on this itr variable. Calling next() starts the generator and it runs until it hits a yield. Then it returns the object with value and done, where the value has the expression value. This expression can be anything. At this point, it pauses execution. Again when we call this function(next), the generator resumes execution from the last yield point with the function state being the same at the time of pause, till the next yield point. This is done till there are no more yield points in the code. Generators in Koa So why are we discussing generators in this tutorial. As you might remember from the hello world program, we used a function* () notation to pass a callback to app.use(). Koa is an object, which contains an array of middleware generator functions, all of which are composed and executed in a stack-like manner upon each request. Koa also implements downstreaming followed by upstreaming of control flow. 6

11 Take a look at the following example to understand this in a better way. var koa = require('koa'); var app = koa(); app.use(function* (next) { //do something before yielding to next generator function //in line which will be 1st event in downstream console.log("1"); yield next; ); // do something when the execution returns upstream, //this will be last event in upstream console.log("2"); app.use(function* (next) { // This shall be 2nd event downstream console.log("3"); yield next; ); // This would be 2nd event upstream console.log("4"); app.use(function* () { // Here it would be last function downstream console.log("5"); // Set response body this.body = "Hello Generators"; ); // First event of upstream (from the last to first) console.log("6"); app.listen(3000); 7

12 When running the above code and navigating to we get the following output on our console This is essentially how Koa uses generators. It allows us to create compact middleware using this property and write code for both upstream and downstream functionalities, thus saving us from callbacks. 8

13 5. Koa.js Routing Koa.js 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(); _.get('/hello', getmessage); // Instantiate the router // Define routes function *getmessage(){ ; this.body = "Hello world!"; app.use(_.routes()); app.listen(3000); // Use the routes defined using the router 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. 9

14 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()); app.listen(3000); // Use the routes defined using the router To test this request, open your terminal and use curl to execute the following request curl -X POST " 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"; ; 10

15 6. Koa.js URL Building Koa.js 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 You will get the following response. 11

16 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 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. 12

17 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: 13

18 7. Koa.js HTTP Methods Koa.js The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table summarizes the commonly used HTTP methods. Method GET POST PUT DELETE Description The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI. The PUT method requests that the server accept the data enclosed in the request as a modification to the existing object identified by the URI. If it does not exist, then PUT method should create one. The DELETE method requests that the server delete the specified resource. These are the most common HTTP methods. To learn more about them, head over to 14

19 8. Koa.js Request Object Koa.js A Koa Request object is an abstraction on top of node's vanilla request object, providing additional functionality 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.listen(3000); When you run this code and navigate to then you will receive the following response. 15

20 On your console, you'll get the request object logged out. { method: 'GET', url: '/hello/', header: { host: 'localhost:3000', connection: 'keep-alive', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/ (KHTML, like Gecko) Chrome/ Safari/537.36', accept: 'text/html,application/xhtml+xml,application/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 then we'll get the following object. 16

21 { 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 Request. 17

22 9. Koa.js Response Object Koa.js A Koa Response object is an abstraction on top of node's vanilla response object, providing additional functionality that is useful for everyday HTTP server development. The Koa response object is embedded in the context object, this. Let s log out the response 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(){ this.body = 'Your request has been logged.'; console.log(this.response); app.use(_.routes()); app.listen(3000); When you run this code and navigate to then you'll receive the following response. 18

23 On your console, you'll get the request object logged out. { status: 200, message: 'OK', header: { 'content-type': 'text/plain; charset=utf-8', 'content-length': '12', body: 'Your request has been logged.' The status and message are automatically set by Koa but can be modified by us. If we don t set the response body, the status code is set to 404. Once we set the response body, the status is set to 200 by default. We can explicitly override this behavior. We have access to many useful properties of the response using this object. Let us look at some examples: response.header Provides all the response headers. response.status Provides the response status (200, 404, 500, etc). This property is also used to set the response status. response.message Provides the response message. This property is also used to set custom messages with responses. It is associated with response.status. response.body Get or set the response body. Usually, we access it using the context object. This is just another way to access it. The body could be of the type: String, Buffer, Stream, Object or Null. response.type Get or set the content type of the current response. response.get(field) This function is used to get the values of headers with case insensitive value field. response.set(field, value) This function is used to set a header on the response using field and value pair. 19

24 response.remove(field) This function is used to unset a header on the response using a field name. You can read more about the response object in the docs at Response. 20

25 10. Koa.js Redirects Koa.js 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); 21

26 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 we get: If we navigate to any other route, we get: 22

27 11. Koa.js Error Handling Koa.js 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); 23

28 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. (/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. 24

29 12. Koa.js Cascading Koa.js 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 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 25

30 _.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 middleware 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 middleware 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. "); 26

31 ; 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. 27

32 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. 28

33 13. Koa.js Templating Koa.js 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 body title="hello Pug" p.greetings#people Hello Views! 29

34 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> </head> <body> </html> </body> <title>hello Pug</title> <p class="greetings" id="people">hello Views!</p> 30

35 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 separated: 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--> 31

36 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:" ); ; app.use(_.routes()); app.listen(3000); // Use the routes defined using the router 32

37 Then, create a new view file in the views directory, named dynamic.pug, using the following code. html head body title= name 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 body title= name h1 Greetings from #{name a(href= url) URL This method of using values is called interpolation. 33

38 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 body title Simple template if(user) else h1 Hi, #{user.name 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 34

39 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'); var pug = new Pug({ viewpath: './views', basedir: './views', app: app //Equivalent to app.use(pug) ); var _ = router(); // Instantiate the router _.get('/components', getcomponents); function *getcomponents(){ this.render('content.pug'); app.use(_.routes()); app.listen(3000); // Use the routes defined using the router 35

40 Go to localhost:3000/components, you should get the following output. include can also be used to include plaintext, CSS and JavaScript. There are many other features of Pug. However, those are out of the scope for this tutorial. You can further explore Pug at Pug. 36

41 14. Koa.js Form Data Koa.js Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the koa-body. To install this, go to your terminal and use: $ npm install --save koa-body Replace your app.js file contents with the following code. 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 //Equivalent to app.use(pug) ); //Set up body parsing middleware app.use(bodyparser({ formidable:{uploaddir: './uploads', multipart: true, urlencoded: true )); _.get('/', renderform); _.post('/', handleform); function * renderform(){ this.render('form'); function *handleform(){ console.log(this.request.body); 37

42 console.log(this.req.body); this.body = this.request.body; //This is where the parsed request is stored app.use(_.routes()); app.listen(3000); The new things we are doing here are importing the body parser and multer. We are using the body parser for parsing json and x-www-form-urlencoded header requests, while we use multer for parsing multipart/form-data. Let us create a html form to test this out! Create a new view named form.pug with the following code. html head body title Form Tester form(action="/", method="post") div br div br Run your server using: nodemon index.js label(for="say") Say: input(name="say" value="hi") label(for="to") To: input(name="to" value="koa form") button(type="submit") Send my greetings 38

43 Now go to localhost:3000/ and fill the form as you like, and submit it. You'll receive the response as: Take a look at your console, it'll show you the body of your request as a JavaScript object. For example: The this.request.body object contains your parsed request body. To use fields from that object, just use them as normal JS objects. This is just one way to send a request. There are many other ways, but those are irrelevant to cover here, because our Koa app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page. 39

44 15. Koa.js File Uploading Koa.js 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 body title File uploads form(action="/upload" method="post" enctype="multipart/form-data") div div div input(type="text" name="name" placeholder="name") input(type="file" name="image") 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({ 40

45 formidable:{uploaddir: './uploads', multipart: true, urlencoded: true )); // This is where the files would come 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. 41

46 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. 42

47 16. Koa.js Static Files Koa.js 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 You should get the following output. Note that this is not a HTML document or Pug view, rather it is a simple txt file. 43

48 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. 44

49 17. Koa.js Cookies Koa.js 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.cookie.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" 45

50 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 ms from the time it is set. this.cookies.set('name', 'value', { httponly: false, expires: Date.now() ); 46

51 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 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. 47

52 18. Koa.js Sessions Koa.js 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. 48

53 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. 49

54 19. Koa.js Authentication Koa.js Authentication is a process in which the credentials provided are compared to those on file in the database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access. We'll be creating a very basic authentication system that'll use Basic HTTP Authentication. This is the simplest possible way to enforce access control as it doesn't require cookies, sessions, or anything else. To use this, the client has to send the Authorization header along with every request it makes. The username and password are not encrypted, but are concatenated in a single string like the following. username:password This string is encoded with Base64, and the word Basic is put before this value. For example, if your username is Ayush and password India, then the string "Ayush:India" would be sent as encoded in the authorization header. Authorization: Basic QXl1c2g6SW5kaWE= To implement this in your koa app, you'll need the koa-basic-auth middleware. Install it using: $ npm install --save koa-basic-auth Now open your app.js file and enter the following code in it. //This is what the authentication would be checked against var credentials = { name: 'Ayush', pass: 'India' var koa = require('koa'); var auth = require('koa-basic-auth'); var _ = require('koa-router')(); var app = koa(); //Error handling middleware app.use(function *(next){ try { yield next; catch (err) { if (401 == err.status) { 50

55 ); this.status = 401; this.set('www-authenticate', 'Basic'); this.body = 'You have no access here'; else { throw err; // Set up authentication here as first middleware. This returns an error if user is not authenticated. _.get('/protected', auth(credentials), function *(){ ); this.body = 'You have access to the protected area.'; yield next; // No authentication middleware present here. _.get('/unprotected', function*(next){ this.body = "Anyone can access this area"; yield next; ); app.use(_.routes()); app.listen(3000); We have created an error handling middleware to handle all authentication related errors. Then, we have created 2 routes: /protected - This route can only be accessed if the user sends the correct authentication header. For all others, it'll give an error. /unprotected - This route can be accessed by anyone, with or without the authentication. Now if you send a request to /protected without an authentication header or with the wrong credentials, you'll receive an error. For example, $ curl You'll receive the response as: 51

56 HTTP/ Unauthorized WWW-Authenticate: Basic Content-Type: text/plain; charset=utf-8 Content-Length: 28 Date: Sat, 17 Sep :05:56 GMT Connection: keep-alive Please authenticate yourself However, with the right credentials, you'll get the expected response. For example, $ curl -H "Authorization: basic QXl1c2g6SW5kaWE=" -i You'll get the response as: HTTP/ OK Content-Type: text/plain; charset=utf-8 Content-Length: 38 Date: Sat, 17 Sep :07:33 GMT Connection: keep-alive You have access to the protected area. The /unprotected route is still accessible to everyone. 52

57 20. Koa.js Compression Koa.js Compression is a simple, effective way to save bandwidth and speed up your site. It is only compatible with modern browsers and should be used with caution if your users use legacy browsers as well. When sending responses from the server, if compression is used, it can greatly improve the load time. We'll be using a middleware called koa-compress to take care of the compression of files as well as setting appropriate headers. Go ahead and install the middleware using: $ npm install --save koa-compress Now in your app.js file, add 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 //Equivalent to app.use(pug) ); app.use(compress({ filter: function (content_type) { return /text/i.test(content_type), threshold: 2048, flush: require('zlib').z_sync_flush )); var _ = router(); // Instantiate the router _.get('/', getroot); function *getroot(next){ 53

58 this.render('index'); app.use(_.routes()); app.listen(3000); // Use the routes defined using the router This puts our compression middleware in place. The filter option is a function that checks the response content type to decide whether to compress. The threshold option is the minimum response size in bytes to compress. This ensures we don t compress every little response. Following is a response without compression. 54

59 Following is the similar response with compression. If you look at the size tab at the bottom, you can very well see the difference between the two. There is more than 150% improvement, when we compress the files. 55

60 21. Koa.js Caching Koa.js 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. 56

61 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. 57

62 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. 58

63 22. Koa.js Database Koa.js We are receiving the requests, but are not storing them anywhere. We need a Database to store the data. We'll use a famous NoSQL database called MongoDB. To install and read about Mongo, head over to this link. In order to use Mongo with Koa, we need a client API for the node. There are multiple options for us, however for this tutorial we'll stick to mongoose. Mongoose is used for document modeling in Node for MongoDB. Document modeling means that, we will create a Model (much like a class in document-oriented programming), and then we will produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these "documents", then finally, we will write these documents in our database. Setting Up Mongoose Now that we have Mongo installed, let us install mongoose, the same way we have been installing our other node packages. $ npm install --save mongoose Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter "mongo". A Mongo shell will start, enter the following. use my_db A new database will be created for you. Whenever you open the Mongo shell, it'll default to "test" db and you'll have to change to your database using the same command as above. To use mongoose, we will require it in our app.js file and then connect to the mongod service running on mongodb://localhost var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); app.use(_.routes()); app.listen(3000); Now our app is connected to our database, let s create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any routes. 59

64 var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); app.use(_.routes()); app.listen(3000); The above code defines the schema for a person and is used to create a mongoose Model Person. Saving Documents Now we will create a new html form, which will get the details of a person and save it to our database. To create the form, create a new view file called person.pug in the views directory with the following content. html head body title Person form(action="/person", method="post") div br div br label(for="name") Name: input(name="name") label(for="age") Age: input(name="age") 60

65 div label(for="nationality") Nationality: input(name="nationality") br button(type="submit") Create new person Also add a new get route in index.js to render this document. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); _.get('/person', getperson); function *getperson(next){ this.render('person'); yield next; app.use(_.routes()); app.listen(3000); 61

66 Go to localhost:3000/person to check if our form is displaying right. Note that this is just the UI, it s not working yet. This is how our form looks. We'll now define a post route handler at '/person' which will handle this request. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); _.post('/person', createperson); function *createperson(next){ var self = this; var personinfo = self.request.body; // Get the parsed information 62

67 if(!personinfo.name!personinfo.age!personinfo.nationality){ self.render('show_message', {message: "Sorry, you provided wrong info", type: "error"); else{ var newperson = new Person({ ); name: personinfo.name, age: personinfo.age, nationality: personinfo.nationality yield newperson.save(function(err, res){ if(err) else self.render('show_message', {message: "Database error", type: "error"); self.render('show_message', {message: "New person added", type: "success", person: personinfo); ); app.use(_.routes()); app.listen(3000); In the above code, if we receive any empty field or do not receive any field, we will send an error response. However, if we receive a well-formed document, then we create a newperson document from the Person model and save it to our DB using newperson.save() function. This is defined in mongoose and accepts a callback as argument. This callback has two arguments, error and response. This will render show_message view, so we need to create that as well. To show the response from this route, we will also need to create a show_message view. Create a new view with the following code. html head body title Person if(type="error") else h3(style="color:red") #{message h3 New person, name: #{person.name, age: #{person.age and nationality: #{person.nationality added! 63

68 Following is the response we receive on successfully submitting the form (show_message.pug). We now have an interface to create persons! Retrieving Documents Mongoose provides a lot of functions for retrieving documents, we will focus on three of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are: Model.find(conditions, callback) This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example, this will fetch all the documents from the persons collection. Person.find(function(err, response){ ); console.log(response); This will fetch all documents where the field name is "Ayush" and age is 20. Person.find({name: "Ayush", age: 20, function(err, response){ ); console.log(response); 64

69 We can also provide the projection we need, i.e., the fields we need. For example, if we want only the names of the people whose nationality is "Indian", we use: Person.find({nationality: "Indian", "name", function(err, response){ ); console.log(response); Model.findOne(conditions, callback) This functions always fetches a single, most relevant document. It has the same exact arguments as Model.find(). Model.findById(id, callback) This function takes in the _id (defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example, Person.findById("507f1f77bcf86cd ", function(err, response){ ); console.log(response); Let's create a route to view all people records. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); _.get('/people', getpeople); function *getpeople(next){ 65

70 var self = this; yield Person.find(function(err, response){ self.body = response; ); app.use(_.routes()); app.listen(3000); Updating Documents Mongoose provides three functions to update documents. Model.update(condition, updates, callback) This function takes a condition and an updates the object as input and applies the changes to all the documents matching the conditions in the collection. For example, the following code will update all Person documents to have a nationality "American". Person.update({age: 25, {nationality: "American", function(err, response){ ); console.log(response); Model.findOneAndUpdate(condition, updates, callback) It does exactly what is says. Finds one document based on the query and updates that according to the second argument. It also takes a callback as the last argument. For example, Person.findOneAndUpdate({name: "Ayush", {age: 40, function(err, response){ ); console.log(response); Model.findByIdAndUpdate(id, updates, callback) This function updates a single document identified by its id. For example, Person.findByIdAndUpdate("507f1f77bcf86cd ", {name: "James", function(err, response){ ); console.log(response); 66

71 Let s create a route to update people. This will be a PUT route with the id as a parameter and details in the payload. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); _.put('/people/:id', updateperson); function *updateperson(){ var self = this; yield Person.findByIdAndUpdate(self.params.id, {$set: {self.request.body, function(err, response){ ); if(err) { else { app.use(_.routes()); app.listen(3000); self.body = {message: "Error in updating person with id " + self.params.id; self.body = response; To test this route, enter the following in your terminal (replace the id with an id from your created people). curl -X PUT --data "name=james&age=20&nationality=american" 67

72 This will update the document associated with the id provided in the route with the above details. Deleting Documents We have covered Create, Read and Update, now we'll see how mongoose can be used to Delete documents. There are three functions here, exactly like update. Model.remove(condition, [callback]) This function takes a condition object as input and removes all the documents matching the conditions. For example, if we need to remove all people aged 20, Person.remove({age:20); Model.findOneAndRemove(condition, [callback]) This functions removes a single, most relevant document according to conditions object. For example, Person.findOneAndRemove({name: "Ayush"); Model.findByIdAndRemove(id, [callback]) This function removes a single document identified by its id. For example, Person.findByIdAndRemove("507f1f77bcf86cd "); Now let s create a route to delete people from our database. var koa = require('koa'); var _ = require('koa-router')(); var app = koa(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personschema = mongoose.schema({ name: String, age: Number, nationality: String ); var Person = mongoose.model("person", personschema); _.delete('/people/:id', deleteperson); function *deleteperson(next){ var self = this; 68

73 yield Person.findByIdAndRemove(self.params.id, function(err, response){ ); if(err) { else{ app.use(_.routes()); app.listen(3000); self.body = {message: "Error in deleting record id " + self.params.id; self.body = {message: "Person with id " + self.params.id + " removed."; To test this out, use the following curl command: curl -X DELETE This will remove the person with the given id producing the following message. {message: "Person with id 507f1f77bcf86cd removed." This wraps up how we can create simple CRUD applications using MongoDB, mongoose and Koa. To explore mongoose further, read the API docs. 69

74 23. Koa.js RESTful APIs Koa.js 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 DELETE /movies/1234 Idempotent /movies/1234 Idempotent Modifies movie id 1234 (creates one if it doesn't already exist). Response contains the URI for this newly created resource. 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(); 70

75 // 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; 71

76 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,"ratin g":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){ else{ this.body = currmovie[0]; this.response.status = 404;//Set status to 404 as movie was not found this.body = {message: "Not Found"; yield next; 72

77 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; 73

78 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" 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, 74

79 ); 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 doesn't exist, it'll create a new object. To test out this route, use the following curl command. This will update an existing movie. To create a new Movie, just change the id to a non-existing id. curl -X PUT --data "name=toy%20story&year=1995&rating=8.5" Response: {"message":"movie id 101 updated.","location":"/movies/101" DELETE Route Use the following code to create a delete route. router.delete('/:id', deletemoviewithid); function *deletemoviewithid(next){ var removeindex = movies.map(function(movie){ return movie.id; ).indexof(this.params.id); // Gets us the index of movie with given id. 75

80 if(removeindex === -1){ this.body = {message: "Not found"; else{ movies.splice(removeindex, 1); this.body = {message: "Movie id " + this.params.id + " removed."; Test the route in the same way we did for the others. On successful deletion (for example id 105), you will get: {message: "Movie id 105 removed." Finally, our movies.js file looks like: 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 router.get('/', sendmovies); router.get('/:id([0-9]{3,)', sendmoviewithid); router.post('/', addnewmovie); router.put('/:id', updatemoviewithid); router.delete('/:id', deletemoviewithid); function *deletemoviewithid(next){ var removeindex = movies.map(function(movie){ return movie.id; ).indexof(this.params.id); // Gets us the index of movie with given id. if(removeindex === -1){ this.body = {message: "Not found"; 76

81 else{ movies.splice(removeindex, 1); this.body = {message: "Movie id " + this.params.id + " removed."; 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, 77

82 ; year: this.request.body.year, rating: this.request.body.rating this.body = {message: "Movie id " + this.params.id + " updated.", location: "/movies/" + this.params.id; 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; function *sendmovies(next){ this.body = movies; yield next; function *sendmoviewithid(next){ var ctx = this var currmovie = movies.filter(function(movie){ 78

83 ); if(movie.id == ctx.params.id){ return true; if(currmovie.length == 1){ else{ this.body = currmovie[0]; this.response.status = 404; this.body = {message: "Not Found"; yield next; module.exports = router; //Set status to 404 as movie was not found This completes our REST API. Now you can create much more complex applications using this simple architectural style and Koa. 79

84 24. Koa.js Logging Koa.js Logging is quite useful when creating web applications as they tell us where exactly things went wrong. We also get the context for the things that went wrong and can come up with possible solutions for the same. To enable logging in Koa, we need the middleware, koa-logger. Install it using the following command. $ npm install --save-dev koa-logger Now in your application, add the following code to enable logging. var logger = require('koa-logger') var koa = require('koa') var app = koa() app.use(logger()) app.use(function*(){ ) this.body = "Hello Logger"; app.listen(3000) Run this server and visit any route on the server. You should see the logs like: Now if you get an error on a specific route or request, these logs should help you figure out what went wrong in each of them. 80

Node.js. Node.js Overview. CS144: Web Applications

Node.js. Node.js Overview. CS144: Web Applications Node.js Node.js Overview JavaScript runtime environment based on Chrome V8 JavaScript engine Allows JavaScript to run on any computer JavaScript everywhere! On browsers and servers! Intended to run directly

More information

This tutorial is meant for software developers who want to learn how to lose less time on API integrations!

This tutorial is meant for software developers who want to learn how to lose less time on API integrations! CloudRail About the Tutorial CloudRail is an API integration solution that speeds up the process of integrating third-party APIs into an application and maintaining them. It does so by providing libraries

More information

We are assuming you have node installed!

We are assuming you have node installed! Node.js Hosting We are assuming you have node installed! This lesson assumes you've installed and are a bit familiar with JavaScript and node.js. If you do not have node, you can download and install it

More information

This tutorial discusses the basics of PouchDB along with relevant examples for easy understanding.

This tutorial discusses the basics of PouchDB along with relevant examples for easy understanding. About this Tutorial PouchDBis an open source in-browser database API written in JavaScript. It ismodelled after CouchDB a NoSQL database that powers npm. Using this API, we can build applications that

More information

This tutorial is intended to make you comfortable in getting started with the Firebase backend platform and its various functions.

This tutorial is intended to make you comfortable in getting started with the Firebase backend platform and its various functions. Firebase About the Tutorial Firebase is a backend platform for building Web, Android and IOS applications. It offers real time database, different APIs, multiple authentication types and hosting platform.

More information

COMP 2406: Fundamentals of Web Applications. Fall 2013 Mid-Term Exam Solutions

COMP 2406: Fundamentals of Web Applications. Fall 2013 Mid-Term Exam Solutions COMP 2406: Fundamentals of Web Applications Fall 2013 Mid-Term Exam Solutions 1. ( false ) HTTP cookies are only sent to a web server when explicitly requested. 2. ( false ) Cookies are normally parsed

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Laravel

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Laravel About the Tutorial Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell.

More information

Client Side JavaScript and AJAX

Client Side JavaScript and AJAX Client Side JavaScript and AJAX Client side javascript is JavaScript that runs in the browsers of people using your site. So far all the JavaScript code we've written runs on our node.js server. This is

More information

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web

Persistence & State. SWE 432, Fall 2016 Design and Implementation of Software for the Web Persistence & State SWE 432, Fall 2016 Design and Implementation of Software for the Web Today What s state for our web apps? How do we store it, where do we store it, and why there? For further reading:

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. WordPress

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. WordPress About the Tutorial WordPress is an open source Content Management System (CMS), which allows the users to build dynamic websites and blog. WordPress is the most popular blogging system on the web and allows

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Meteor

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Meteor About the Tutorial Meteor is a full-stack JavaScript platform for building web and mobile apps. Meteor makes it easier to create real-time apps, since it alone offers a full ecosystem to work with, instead

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer ASP.NET WP

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer ASP.NET WP i About the Tutorial This tutorial will give you a fair idea on how to get started with ASP.NET Web pages. Microsoft ASP.NET Web Pages is a free Web development technology that is designed to deliver the

More information

What is Node.js? Tim Davis Director, The Turtle Partnership Ltd

What is Node.js? Tim Davis Director, The Turtle Partnership Ltd What is Node.js? Tim Davis Director, The Turtle Partnership Ltd About me Co-founder of The Turtle Partnership Working with Notes and Domino for over 20 years Working with JavaScript technologies and frameworks

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Drupal

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Drupal About the Tutorial is a free and open source Content Management System (CMS) that allows organizing, managing and publishing your content. This reliable and secure CMS is built on PHP based environment

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming About the Tutorial Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional

More information

Penetration Test Report

Penetration Test Report Penetration Test Report Feb 12, 2018 Ethnio, Inc. 6121 W SUNSET BLVD LOS angeles, CA 90028 Tel (888) 879-7439 ETHN.io Summary This document contains the most recent pen test results from our third party

More information

Hands-on Lab Session 9011 Working with Node.js Apps in IBM Bluemix. Pam Geiger, Bluemix Enablement

Hands-on Lab Session 9011 Working with Node.js Apps in IBM Bluemix. Pam Geiger, Bluemix Enablement Hands-on Lab Session 9011 Working with Node.js Apps in IBM Bluemix Pam Geiger, Bluemix Enablement Copyright IBM Corporation 2017 IBM, the IBM logo and ibm.com are trademarks of International Business Machines

More information

IERG 4210 Tutorial 08

IERG 4210 Tutorial 08 IERG 4210 Tutorial 08 Securing web page (II): - In principle: Cookie related security issues - In practice: Point by point checklist for Phase 4A Shizhan Zhu Logistics Content for today: Provide sample

More information

CSCU9B2 Practical 1: Introduction to HTML 5

CSCU9B2 Practical 1: Introduction to HTML 5 CSCU9B2 Practical 1: Introduction to HTML 5 Aim: To learn the basics of creating web pages with HTML5. Please register your practical attendance: Go to the GROUPS\CSCU9B2 folder in your Computer folder

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Joomla

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Joomla About the Tutorial Joomla is an open source Content Management System (CMS), which is used to build websites and online applications. It is free and extendable which is separated into frontend templates

More information

Index. Backbone.js app, 274 Behavior-driven development (BDD) language, 252 bodyparser() method, 257

Index. Backbone.js app, 274 Behavior-driven development (BDD) language, 252 bodyparser() method, 257 Index A Abstraction dirname global variable, 159 middleware, 155, 158 module.exports, 160 query string parameter, 158 routes, 156, 158 AngelList API, 278 app.configure() method, 47 application.js modules,

More information

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. TurboGears

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. TurboGears About the Tutorial TurboGears is a Python web application framework, which consists of many modules. It is designed around the MVC architecture that are similar to Ruby on Rails or Struts. TurboGears are

More information

Manual Html A Href Onclick Submit Form

Manual Html A Href Onclick Submit Form Manual Html A Href Onclick Submit Form JS HTML DOM. DOM Intro DOM Methods HTML form validation can be done by a JavaScript. If a form field _input type="submit" value="submit" /form_. As shown in a previous

More information

Microservices with Node.js

Microservices with Node.js Microservices with Node.js Objectives In this module we will discuss: Core Node.js concepts Node Package Manager (NPM) The Express Node.js package The MEAN stack 1.1 What is Node.js? Node.js [ https://nodejs.org/

More information

6/27/2017 Koa - next generation web framework for node.js. koa. next generation web framework for node.js. 1/34

6/27/2017 Koa - next generation web framework for node.js. koa. next generation web framework for node.js.  1/34 koa next generation web framework for node.js http://koajs.com/ 1/34 Introduction Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust

More information

This tutorial is designed for software programmers who would like to learn the basics of ASP.NET Core from scratch.

This tutorial is designed for software programmers who would like to learn the basics of ASP.NET Core from scratch. About the Tutorial is the new web framework from Microsoft. is the framework you want to use for web development with.net. At the end this tutorial, you will have everything you need to start using and

More information

This tutorial has been prepared for beginners to help them understand the basic functionalities of Gulp.

This tutorial has been prepared for beginners to help them understand the basic functionalities of Gulp. About the Tutorial Gulp is a task runner that uses Node.js as a platform. It purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. Gulp builds system automated

More information

AngularJS Intro Homework

AngularJS Intro Homework AngularJS Intro Homework Contents 1. Overview... 2 2. Database Requirements... 2 3. Navigation Requirements... 3 4. Styling Requirements... 4 5. Project Organization Specs (for the Routing Part of this

More information

COMP 2406: Fundamentals of Web Applications. Winter 2014 Mid-Term Exam Solutions

COMP 2406: Fundamentals of Web Applications. Winter 2014 Mid-Term Exam Solutions COMP 2406: Fundamentals of Web Applications Winter 2014 Mid-Term Exam Solutions 1. ( true ) The Register button on / causes a form to be submitted to the server. 2. ( false ) In JavaScript, accessing object

More information

Detects Potential Problems. Customizable Data Columns. Support for International Characters

Detects Potential Problems. Customizable Data Columns. Support for International Characters Home Buy Download Support Company Blog Features Home Features HttpWatch Home Overview Features Compare Editions New in Version 9.x Awards and Reviews Download Pricing Our Customers Who is using it? What

More information

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire

More information

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web

Persistence. SWE 432, Fall 2017 Design and Implementation of Software for the Web Persistence SWE 432, Fall 2017 Design and Implementation of Software for the Web Today Demo: Promises and Timers What is state in a web application? How do we store it, and how do we choose where to store

More information

Backend Development. SWE 432, Fall 2017 Design and Implementation of Software for the Web

Backend Development. SWE 432, Fall 2017 Design and Implementation of Software for the Web Backend Development SWE 432, Fall 2017 Design and Implementation of Software for the Web Real World Example https://qz.com/1073221/the-hackers-who-broke-into-equifax-exploited-a-nine-year-old-security-flaw/

More information

HTTP Server Application

HTTP Server Application 1 Introduction You are to design and develop a concurrent TCP server that implements the HTTP protocol in the form of what is commonly called a web server. This server will accept and process HEAD and

More information

INTERNET ENGINEERING. HTTP Protocol. Sadegh Aliakbary

INTERNET ENGINEERING. HTTP Protocol. Sadegh Aliakbary INTERNET ENGINEERING HTTP Protocol Sadegh Aliakbary Agenda HTTP Protocol HTTP Methods HTTP Request and Response State in HTTP Internet Engineering 2 HTTP HTTP Hyper-Text Transfer Protocol (HTTP) The fundamental

More information

NODE.JS MOCK TEST NODE.JS MOCK TEST I

NODE.JS MOCK TEST NODE.JS MOCK TEST I http://www.tutorialspoint.com NODE.JS MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Node.js Framework. You can download these sample mock tests at

More information

Developing Ajax Applications using EWD and Python. Tutorial: Part 2

Developing Ajax Applications using EWD and Python. Tutorial: Part 2 Developing Ajax Applications using EWD and Python Tutorial: Part 2 Chapter 1: A Logon Form Introduction This second part of our tutorial on developing Ajax applications using EWD and Python will carry

More information

Smashing Node.JS: JavaScript Everywhere

Smashing Node.JS: JavaScript Everywhere Smashing Node.JS: JavaScript Everywhere Rauch, Guillermo ISBN-13: 9781119962595 Table of Contents PART I: GETTING STARTED: SETUP AND CONCEPTS 5 Chapter 1: The Setup 7 Installing on Windows 8 Installing

More information

Unifer Documentation. Release V1.0. Matthew S

Unifer Documentation. Release V1.0. Matthew S Unifer Documentation Release V1.0 Matthew S July 28, 2014 Contents 1 Unifer Tutorial - Notes Web App 3 1.1 Setting up................................................. 3 1.2 Getting the Template...........................................

More information

Using OAuth 2.0 to Access ionbiz APIs

Using OAuth 2.0 to Access ionbiz APIs Using OAuth 2.0 to Access ionbiz APIs ionbiz APIs use the OAuth 2.0 protocol for authentication and authorization. ionbiz supports common OAuth 2.0 scenarios such as those for web server, installed, and

More information

Elevate Web Builder Modules Manual

Elevate Web Builder Modules Manual Table of Contents Elevate Web Builder Modules Manual Table Of Contents Chapter 1 - Getting Started 1 1.1 Creating a Module 1 1.2 Handling Requests 3 1.3 Custom DataSet Modules 8 Chapter 2 - Component Reference

More information

Assignment, part 2. Statement and concepts INFO-0010

Assignment, part 2. Statement and concepts INFO-0010 Assignment, part 2 Statement and concepts INFO-0010 Outline Statement Implementation of concepts Objective Mastermind game using HTTP GET and HTTP POST methods The platform Architecture Root page ("/")

More information

Cookies, sessions and authentication

Cookies, sessions and authentication Cookies, sessions and authentication TI1506: Web and Database Technology Claudia Hauff! Lecture 7 [Web], 2014/15 1 Course overview [Web] 1. http: the language of Web communication 2. Web (app) design &

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 07 Tutorial 2 Part 1 Facebook API Hi everyone, welcome to the

More information

Cloud Help for Community Managers...3. Release Notes System Requirements Administering Jive for Office... 6

Cloud Help for Community Managers...3. Release Notes System Requirements Administering Jive for Office... 6 for Office Contents 2 Contents Cloud Help for Community Managers...3 Release Notes... 4 System Requirements... 5 Administering Jive for Office... 6 Getting Set Up...6 Installing the Extended API JAR File...6

More information

The HTTP protocol. Fulvio Corno, Dario Bonino. 08/10/09 http 1

The HTTP protocol. Fulvio Corno, Dario Bonino. 08/10/09 http 1 The HTTP protocol Fulvio Corno, Dario Bonino 08/10/09 http 1 What is HTTP? HTTP stands for Hypertext Transfer Protocol It is the network protocol used to delivery virtually all data over the WWW: Images

More information

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Django

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Django About the Tutorial Django is a web development framework that assists in building and maintaining quality web applications. Django helps eliminate repetitive tasks making the development process an easy

More information

Connector for Microsoft SharePoint 2013, 2016 and Online Setup and Reference Guide

Connector for Microsoft SharePoint 2013, 2016 and Online Setup and Reference Guide Connector for Microsoft SharePoint 2013, 2016 and Online Setup and Reference Guide Published: 2018-Oct-09 Contents 1 Microsoft SharePoint 2013, 2016 and Online Connector 4 1.1 Products 4 1.2 Supported

More information

COSC 2206 Internet Tools. The HTTP Protocol

COSC 2206 Internet Tools. The HTTP Protocol COSC 2206 Internet Tools The HTTP Protocol http://www.w3.org/protocols/ What is TCP/IP? TCP: Transmission Control Protocol IP: Internet Protocol These network protocols provide a standard method for sending

More information

jquery Basic HTTP communication

jquery Basic HTTP communication jquery Basic HTTP communication TAMZ 1 Lab 5 See: http://api.jquery.com/jquery.get/ http://api.jquery.com/jquery.post/ Application deployment Application has to be uploaded to a server Using of FTP/SCP/SFTP

More information

Nasuni Data API Nasuni Corporation Boston, MA

Nasuni Data API Nasuni Corporation Boston, MA Nasuni Corporation Boston, MA Introduction The Nasuni API has been available in the Nasuni Filer since September 2012 (version 4.0.1) and is in use by hundreds of mobile clients worldwide. Previously,

More information

Browser behavior can be quite complex, using more HTTP features than the basic exchange, this trace will show us how much gets transferred.

Browser behavior can be quite complex, using more HTTP features than the basic exchange, this trace will show us how much gets transferred. Lab Exercise HTTP Objective HTTP (HyperText Transfer Protocol) is the main protocol underlying the Web. HTTP functions as a request response protocol in the client server computing model. A web browser,

More information

Introduction to HTTP. Jonathan Sillito

Introduction to HTTP. Jonathan Sillito Introduction to HTTP Jonathan Sillito If you interested in working with a professor next Summer 2011 apply for an NSERC Undergraduate Student Award. Students must have a GPA of 3.0 or higher to be eligible.

More information

How to work with HTTP requests and responses

How to work with HTTP requests and responses How a web server processes static web pages Chapter 18 How to work with HTTP requests and responses How a web server processes dynamic web pages Slide 1 Slide 2 The components of a servlet/jsp application

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. RichFaces

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. RichFaces 1 About the Tutorial RichFaces is a component library developed by JBoss, which provides in-built AJAX support to JSF application. It reduces all the redundant codes that the developer has to write to

More information

Catbook Workshop: Intro to NodeJS. Monde Duinkharjav

Catbook Workshop: Intro to NodeJS. Monde Duinkharjav Catbook Workshop: Intro to NodeJS Monde Duinkharjav What is NodeJS? NodeJS is... A Javascript RUNTIME ENGINE NOT a framework NOT Javascript nor a JS package It is a method for running your code in Javascript.

More information

Configuring Request Authentication and Authorization

Configuring Request Authentication and Authorization CHAPTER 15 Configuring Request Authentication and Authorization Request authentication and authorization is a means to manage employee use of the Internet and restrict access to online content. This chapter

More information

Copyright by Object Computing, Inc. (OCI). All rights reserved. Strata

Copyright by Object Computing, Inc. (OCI). All rights reserved. Strata Overview npm install [-g] strata var strata = require('strata'); Node.js streaming HTTP server Based on Web Server Gateway Interface (WSGI) - a Python standard at http://wsgi.org Rack - a Ruby Webserver

More information

Nasuni Data API Nasuni Corporation Boston, MA

Nasuni Data API Nasuni Corporation Boston, MA Nasuni Corporation Boston, MA Introduction The Nasuni API has been available in the Nasuni Filer since September 2012 (version 4.0.1) and is in use by hundreds of mobile clients worldwide. Previously,

More information

Quick.JS Documentation

Quick.JS Documentation Quick.JS Documentation Release v0.6.1-beta Michael Krause Jul 22, 2017 Contents 1 Installing and Setting Up 1 1.1 Installation................................................ 1 1.2 Setup...................................................

More information

Sessions. Mendel Rosenblum. CS142 Lecture Notes - Sessions

Sessions. Mendel Rosenblum. CS142 Lecture Notes - Sessions Sessions Mendel Rosenblum How do we know what user sent request? Would like to authenticate user and have that information available each time we process a request. More generally web apps would like to

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. GraphQL

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. GraphQL i About the Tutorial GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls. It is an execution engine and a data query language. This tutorial will

More information

In this tutorial, we are going to learn how to use the various features available in Flexbox.

In this tutorial, we are going to learn how to use the various features available in Flexbox. About the Tutorial Flexbox (flexible box) is a layout mode of CSS3. Using this mode, you can easily create layouts for complex applications and web pages. Flexbox layout gives complete control over the

More information

BIG-IP Access Policy Manager : Portal Access. Version 12.1

BIG-IP Access Policy Manager : Portal Access. Version 12.1 BIG-IP Access Policy Manager : Portal Access Version 12.1 Table of Contents Table of Contents Overview of Portal Access...7 Overview: What is portal access?...7 About portal access configuration elements...7

More information

Backend Development. SWE 432, Fall Web Application Development

Backend Development. SWE 432, Fall Web Application Development Backend Development SWE 432, Fall 2018 Web Application Development Review: Async Programming Example 1 second each Go get a candy bar Go get a candy bar Go get a candy bar Go get a candy bar Go get a candy

More information

Introduction & Basics! Technical Foundation! Authentication! Obtaining a token!... 4 Using the token! Working with notes!...

Introduction & Basics! Technical Foundation! Authentication! Obtaining a token!... 4 Using the token! Working with notes!... Simplenote API2 Documentation v2.1.3: (April 18, 2011). Recent documentation changes are listed on the last page. Contents Introduction & Basics!... 3 Technical Foundation!... 3 Authentication!... 4 Obtaining

More information

Session 3: JavaScript - Structured Programming

Session 3: JavaScript - Structured Programming INFM 603: Information Technology and Organizational Context Session 3: JavaScript - Structured Programming Jimmy Lin The ischool University of Maryland Thursday, September 25, 2014 Source: Wikipedia Types

More information

Application Design and Development: October 30

Application Design and Development: October 30 M149: Database Systems Winter 2018 Lecturer: Panagiotis Liakos Application Design and Development: October 30 1 Applications Programs and User Interfaces very few people use a query language to interact

More information

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University 1 Objectives You will learn about Server-side web programming in Python Common Gateway Interface

More information

CMSC 332 Computer Networking Web and FTP

CMSC 332 Computer Networking Web and FTP CMSC 332 Computer Networking Web and FTP Professor Szajda CMSC 332: Computer Networks Project The first project has been posted on the website. Check the web page for the link! Due 2/2! Enter strings into

More information

HTTP Security Headers Explained

HTTP Security Headers Explained HTTP Security Headers Explained Scott Sauber Slides at scottsauber.com scottsauber Audience Anyone with a website Agenda What are HTTP Security Headers? Why do they matter? HSTS, XFO, XSS, CSP, CTO, RH,

More information

8.0 Help for Community Managers Release Notes System Requirements Administering Jive for Office... 6

8.0 Help for Community Managers Release Notes System Requirements Administering Jive for Office... 6 for Office Contents 2 Contents 8.0 Help for Community Managers... 3 Release Notes... 4 System Requirements... 5 Administering Jive for Office... 6 Getting Set Up...6 Installing the Extended API JAR File...6

More information

Human-Computer Interaction Design

Human-Computer Interaction Design Human-Computer Interaction Design COGS120/CSE170 - Intro. HCI Instructor: Philip Guo Lab 6 - Connecting frontend and backend without page reloads (2016-11-03) by Michael Bernstein, Scott Klemmer, and Philip

More information

Lecture 7b: HTTP. Feb. 24, Internet and Intranet Protocols and Applications

Lecture 7b: HTTP. Feb. 24, Internet and Intranet Protocols and Applications Internet and Intranet Protocols and Applications Lecture 7b: HTTP Feb. 24, 2004 Arthur Goldberg Computer Science Department New York University artg@cs.nyu.edu WWW - HTTP/1.1 Web s application layer protocol

More information

Early Data Analyzer Web User Guide

Early Data Analyzer Web User Guide Early Data Analyzer Web User Guide Early Data Analyzer, Version 1.4 About Early Data Analyzer Web Getting Started Installing Early Data Analyzer Web Opening a Case About the Case Dashboard Filtering Tagging

More information

Ninox API. Ninox API Page 1 of 15. Ninox Version Document version 1.0.0

Ninox API. Ninox API Page 1 of 15. Ninox Version Document version 1.0.0 Ninox API Ninox Version 2.3.4 Document version 1.0.0 Ninox 2.3.4 API 1.0.0 Page 1 of 15 Table of Contents Introduction 3 Obtain an API Key 3 Zapier 4 Ninox REST API 5 Authentication 5 Content-Type 5 Get

More information

Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1

Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1 Introduction, Notepad++, File Structure, 9 Tags, Hyperlinks 1 Introduction to HTML HTML, which stands for Hypertext Markup Language, is the standard markup language used to create web pages. HTML consists

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 12 Tutorial 3 Part 1 Twitter API In this tutorial, we will learn

More information

ForeScout CounterACT. Configuration Guide. Version 3.4

ForeScout CounterACT. Configuration Guide. Version 3.4 ForeScout CounterACT Open Integration Module: Data Exchange Version 3.4 Table of Contents About the Data Exchange Module... 4 About Support for Dual Stack Environments... 4 Requirements... 4 CounterACT

More information

django-baton Documentation

django-baton Documentation django-baton Documentation Release 1.3.1 abidibo Nov 05, 2018 Contents 1 Features 3 2 Getting started 5 2.1 Installation................................................ 5 2.2 Configuration...............................................

More information

REST Easy with Infrared360

REST Easy with Infrared360 REST Easy with Infrared360 A discussion on HTTP-based RESTful Web Services and how to use them in Infrared360 What is REST? REST stands for Representational State Transfer, which is an architectural style

More information

ForeScout Open Integration Module: Data Exchange Plugin

ForeScout Open Integration Module: Data Exchange Plugin ForeScout Open Integration Module: Data Exchange Plugin Version 3.2.0 Table of Contents About the Data Exchange Plugin... 4 Requirements... 4 CounterACT Software Requirements... 4 Connectivity Requirements...

More information

StorageGRID Webscale 11.0 Tenant Administrator Guide

StorageGRID Webscale 11.0 Tenant Administrator Guide StorageGRID Webscale 11.0 Tenant Administrator Guide January 2018 215-12403_B0 doccomments@netapp.com Table of Contents 3 Contents Administering a StorageGRID Webscale tenant account... 5 Understanding

More information

Php Manual Header Redirect After 5 Seconds Using

Php Manual Header Redirect After 5 Seconds Using Php Manual Header Redirect After 5 Seconds Using Okay, so I've seen a couple of different approaches for redirecting a user I didn't think it was important but after reading the header manual you are I

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 08 Tutorial 2, Part 2, Facebook API (Refer Slide Time: 00:12)

More information

Practical Node.js. Building Real-World Scalable Web Apps. Apress* Azat Mardan

Practical Node.js. Building Real-World Scalable Web Apps. Apress* Azat Mardan Practical Node.js Building Real-World Scalable Web Apps Azat Mardan Apress* Contents About the Author About the Technical Reviewer Acknowledgments Introduction xv xvii xix xxi Chapter 1: Setting up Node.js

More information

McAfee Next Generation Firewall 5.8.0

McAfee Next Generation Firewall 5.8.0 Reference Guide Revision A McAfee Next Generation Firewall 5.8.0 SMC API This guide gives an overview of the Security Management Center (SMC) application programming interface (API). It describes how to

More information

Ajax HTML5 Cookies. Sessions 1A and 1B

Ajax HTML5 Cookies. Sessions 1A and 1B Ajax HTML5 Cookies Sessions 1A and 1B JavaScript Popular scripting language: Dynamic and loosely typed variables. Functions are now first-class citizens. Supports OOP. var simple = 2; simple = "I'm text

More information

EmberJS A Fitting Face for a D8 Backend. Taylor Solomon

EmberJS A Fitting Face for a D8 Backend. Taylor Solomon EmberJS A Fitting Face for a D8 Backend Taylor Solomon taylor.solomon @jtsolomon http://interactivestrategies.com 2 Years Ago 2 Years Ago URL Ember Data assumes a few things. - Your API format is JSON

More information

delegator Documentation

delegator Documentation delegator Documentation Release 1.0.1 Daniel Knell August 25, 2014 Contents 1 Getting Started 3 1.1 Installation................................................ 3 1.2 Quickstart................................................

More information

VMware AirWatch Integration with F5 Guide Enabling secure connections between mobile applications and your backend resources

VMware AirWatch Integration with F5 Guide Enabling secure connections between mobile applications and your backend resources VMware AirWatch Integration with F5 Guide Enabling secure connections between mobile applications and your backend resources Workspace ONE UEM v9.6 Have documentation feedback? Submit a Documentation Feedback

More information

Learning vrealize Orchestrator in action V M U G L A B

Learning vrealize Orchestrator in action V M U G L A B Learning vrealize Orchestrator in action V M U G L A B Lab Learning vrealize Orchestrator in action Code examples If you don t feel like typing the code you can download it from the webserver running on

More information

HTTP Requests and Header Settings

HTTP Requests and Header Settings Overview, page 1 HTTP Client Requests (HTTP GET), page 1 HTTP Server Requests (HTTP POST), page 2 HTTP Header Settings, page 2 IP Phone Client Capability Identification, page 8 Accept Header, page 9 IP

More information

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies CNIT 129S: Securing Web Applications Ch 3: Web Application Technologies HTTP Hypertext Transfer Protocol (HTTP) Connectionless protocol Client sends an HTTP request to a Web server Gets an HTTP response

More information

Programming for the Web with PHP

Programming for the Web with PHP Aptech Ltd Version 1.0 Page 1 of 11 Table of Contents Aptech Ltd Version 1.0 Page 2 of 11 Abstraction Anonymous Class Apache Arithmetic Operators Array Array Identifier arsort Function Assignment Operators

More information

Ajax Ajax Ajax = Asynchronous JavaScript and XML Using a set of methods built in to JavaScript to transfer data between the browser and a server in the background Reduces the amount of data that must be

More information

Front End Programming

Front End Programming Front End Programming Mendel Rosenblum Brief history of Web Applications Initially: static HTML files only. Common Gateway Interface (CGI) Certain URLs map to executable programs that generate web page

More information

maxecurity Product Suite

maxecurity Product Suite maxecurity Product Suite Domain Administrator s Manual Firmware v2.2 ii Table of Contents BASICS... 1 Understanding how maxecurity products work in your company... 1 Getting started as a Domain Administrator...

More information

TDDC88 Lab 4 Software Configuration Management

TDDC88 Lab 4 Software Configuration Management TDDC88 Lab 4 Software Configuration Management Introduction "Version control is to programmers what the safety net is to a trapeze artist. Knowing the net is there to catch them if they fall, aerialists

More information

Checklist for Testing of Web Application

Checklist for Testing of Web Application Checklist for Testing of Web Application Web Testing in simple terms is checking your web application for potential bugs before its made live or before code is moved into the production environment. During

More information