T8: NodeJS CPSC 513 Dr. P. Federl University of Calgary Arshia Hosseini T01/T02
What is NodeJS • Open source JavaScript framework • Event-driven • Cross-platform • Server-side 2
Installing and Running Node • https://nodejs.org/en/download/ • From command line, run the following command: node myFirst.js • From the web browser access http://localhost:8080 3
Hello World • Simple server code 4
Node HTTP • Fast • But very Low level • Need to handle response codes by hand • Need to handle response types by hand • Need to handle routes by hand • Solution? • Express 5
Express • Minimalist web framework for Node.js • Provides a robust set of features for web and mobile applications. • A thin layer of fundamental web application features, without obscuring Node.js features and its performance • Installation: • npm install express --save 6
Hello world application • Simple code 7
Basic Routing • Routing refers to how an application’s endpoints (URIs) respond to client requests. • app.METHOD(PATH, Handler) • Method can be any of the HTTP Methods • get, post, put, delete, etc. Route PATH is endpoint that will trigger this route. • “/” means that the user has to access your.site/ • “/home” means that the user has to access your.site/home • PATHs can be strings, patterns or regular expressions. • Handler is the function that will be triggered when the user reaches a certain PATH • It takes two parameters • req=request • res=response 8
Application-level middleware • Express is a routing and middleware web framework: An Express application is essentially a series of middleware function calls. • Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle (next). • Middleware functions can perform the following tasks: • Execute any code. • Make changes to the request and the response objects. • End the request-response cycle. • Call the next middleware function in the stack. • The function is executed every time the app receives a request. var app = express() app.use(function (req, res, next) { console.log('Time:', Date.now()) next() }) 9
Response Methods • res parameter • .send( content ) – sends an HTTP Response of various types • Handles response types automatically • You can set them by hand if you want, using .set(‘Content-type’, ‘value), before responding. • .json( content ) – sends a JSON response • .download( content ) – forces the user to download the content • .redirect ( target ) – sends a 302 redirect • .render – Renders a view and sends the rendered HTML string to the client. 10
Request method • req parameter • Properties • .url • .body • .method • .path • Methods • .get(field) • Returns the specified HTTP request header field • .param('name') • Returns the value of param 'name' when present. 11
Embedded JavaScript templating (EJS) • EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. • <% 'Scriptlet' tag, for control-flow, no output • <%= Outputs the value into the template (HTML escaped) • <%# Comment tag, no execution, no output • %> Plain ending tag <% if (user) { %> <h2><%= user.name %></h2> <% } %> 12
• Example: // server.js <!-- views/pages/index.ejs --> ... // index page <h2>Loop</h2> app.get('/', function(req, res) { var drinks = [ <ul> { name: 'Bloody Mary', <% drinks.forEach(function(drink) { drunkness: 3 }, %> { name: 'Martini', drunkness: 5 }, <li><%= drink.name %> - <%= { name: 'Scotch', drunkness: 10 } drink.drunkness %></li> ]; <% }); %> </ul> res.render('pages/index', { ... drinks: drinks }); }); 13
Exercise: Creating a ToDo list • We are going to create a to do list. • The visitor will simply be able to add and remove tasks. • We can add elements to the to do list via the form. • We can delete items by clicking on the crosses in the list. 1. Install NodeJS from the website 2. Download the files from my webpage (T8: Express): • https://pages.cpsc.ucalgary.ca/~seyedarshia.hosseini/courses/seng513/ 3. Use NPM to install the dependencies inside the directory • npm install 4. EJS is used for templating • Take a look at the todo.ejs file in views 5. Add the body of the app.METHODs 14
Defining the routes • Ask the question of what your server should do? • List the tasks. • Add a task. • Delete a task. • We associate a route to each of these features: • /todo: list of tasks. • /todo/add: add a task. • /todo/delete/:id: delete task n°id. 15
Recommend
More recommend