Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web-Technology Lecture 11.

Similar presentations


Presentation on theme: "Web-Technology Lecture 11."— Presentation transcript:

1 Web-Technology Lecture 11

2 Stateful web with AJAX No need to reload entire page
Asynchronous communication between Client and Server User’s interactions are sent, the webpages reacts based on the server responses State can be divided between client and server Position within the application (the flow) in the client Temporary session data is on the client Persistent data is on the server Lennart Herlaar - UU

3 jQuery revisited jQuery supports AJAX Variants of one basic method
In at least 6 different ways ... Variants of one basic method load() – Loads a piece of HTML into an element $.getJSON() – Loads JSON via GET $.getScript() – Loads JavaScript and run it $.get() – Performs a generic GET AJAX call $.post() – Performs a generic POST AJAX call $.ajax() – Performs a generic AJAX call Lennart Herlaar - UU

4 jQuery revisited var ajaxload = "<img src='load.gif' alt='loading...'/>"; $(function(){ $("button").click(function(){ $("div").html(ajaxload).load('test.js'); }); <script type="text/javascript"> $(function(){ $("button").click(function(){ $("div").load('test.js'); }); </script> ... <body> <div> <h2>Let AJAX change this text</h2> </div> <button>Change Content</button> </body> Lennart Herlaar - UU

5 jQuery revisited $(function(){ $("button").click(function(){
$("div").html(ajaxload); $.post("test.js", {"user": "willie", "id": 5}, function(responseText){ $("div").html(responseText);}, "html" ); }); $(function(){ $("button").click(function(){ $("div").html(ajaxload); $.ajax({url : "test.js", type : "GET", dataType : "html", success : function(responseText){ $("div").html(responseText);} }); Lennart Herlaar - UU

6 Express framework

7 Express Connection to Node.js
Express framework is build on top of the Connect framework to make Node.JS web-app development even faster It’s a full-scale webapp development framework similar to Rails for Ruby or Django for Python Arguably, the most popular Node.JS framework de facto standard server framework for Node.js (according to Wikipedia :) Lots of info on Active community Current version is 4.x. Version 5.0 is expected soon to bring full support of ES 2017 (Async functions, Promises ..) and more There are other frameworks built on top of Express.JS But we will not go further :)

8 Who is using express.js: More information here:
The approach Opinionated, minimalist : does not restrict you, instead providing with a reduced set of efficiently implemented most basic components and a flexible way to integrate and extend them What can it do: Routing File handling Who is using express.js: More information here: expressjs.com … and here:

9 Setting up basic Express.js app
Create a directory to hold your webapp, and make that your working directory Create your webapp package specification (package.json) This starts a customization process - you either provide data, or accepts the defaults  Install Express in the ”myapp” directory --save command adds Express to the dependencies in package.json $ mkdir myapp $ cd myapp $ npm init $ npm install express --save

10 Hello world webapp What’s missing? var express = require('express');
var app = express(); app.get('/', function (req, res) { res.send('Hello, World!'); }); app.listen(8081); var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); What’s missing? $ node hello.js

11 Setting a webapp with express-generator
Install it (it installs express command-line tool) Make sure to run this as an administrator, e.g. Create an app and generate it skeleton: Install dependencies $ npm install express-generator -g ├── app.js ├── bin │ └── www ├── package.json ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── routes │ ├── index.js │ └── users.js └── views ├── error.jade ├── index.jade └── layout.jade $ sudo npm install express-generator -g $ express myapp $ cd myapp $ npm install

12 Start your server Start in debug mode: On Windows:
On MacOS and Linux: On Windows: Start in execution mode: $ DEBUG=myapp:* npm start > set DEBUG=myapp:* & npm start $ npm start

13 Basic routing Routing determines how an application responds to a client request to a particular endpoint Each route can have 1 or more handling functions executed with the parameters match app.get('/', function (req, res) { res.send('Hello World!') }) app.post('/', function (req, res) { res.send('Got a POST request') app.put('/user', function (req, res) { res.send('Got a PUT request at /user') app.delete('/user', function (req, res) { res.send('Got a DELETE request at /user')

14 Routing: Not found After all known routes have been processed, a 404 route can be added to handle “not found” situations: app.use(function(request, response) { response.status(404).send("Page not found!"); });

15 Routing: grabbing parameters
You can write customizable routing middleware handling parameterized requests to particular routes (parameters are encoded as named parts of the URL) Grabbed parameters are automatically added to request.params This router will react to a get request to any URL of these kinds: app.get("/users/:userid/products/:productid", function(req, res) { var userId = parseInt(req.params.userid, 10); var productId = parseInt(req.params.productid, 10); // … });

16 Routing: regular expressions
Routes can be specified as RegEx’s E.g. this will enforce that “userid” is an integer: app. get(/^\/users\/(\d+)$/, function(req, res) { var userId = parseInt(req.params[0], 10); res.send('' + userId); })

17 Serving static files Static files (images, CSS, JavaScript files, etc.) can be served using the built-in middleware Such middleware is usually “.use”d in the very beginning to make sure that if there is a static file to serve, it will handle it before the routers kick in It will intercept request to static files and will look for them in the /static/ folder If found the files will be returned to the client E.g., if you have form.html in the /static/ folder, a request like this will work: localhost:8081/form.html If you have form.html in the root directory, client will not be able to access it Put index.html into the /static/ folder for a request like this to work: var express = require("express"); var path = require("path"); var app = express(); var staticPath = path.join(__dirname, "static"); app.use(express.static(staticPath));

18 Routing: splitting your app
As your app grows, you might want to split all the routing options, or at least to separate them from the rest of the app.js // app.js var express = require("express"); var path = require("path"); var apiRouter = require ("./routes/api_router"); var app = express(); var staticPath = path.resolve (__dirname, "static"); app.use(express.static(staticPath)); app.use("/api", apiRouter); app.listen(3000); // api.js var express = require("express"); var api = express.Router(); api.get("/users", function(req, res) { /* ... */ }); api.post("/user", function(req, res) { /* ... */ }); api.get("/messages", function(req, res) { /* ... */ }); api.post("/message", function(req, res) { /* ... */ }); module.exports = api;

19 Routing: other app.methods
app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...') next() // pass control to the next handler }) .all – matches all HTTP methods GET, POST, PUT, DELETE, ….. .route() – creates chainable route handlers for a route path app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') .put(function (req, res) { res.send('Update the book')

20 Routing: other response.methods
Description res.download() Prompt a file to be downloaded. res.end() End the response process. res.json() Send a JSON response. res.redirect() Redirect a request. res.render() Render a view template. res.send() Send a response of various types. res.sendFile() Send a file (better use express.static – it is safe and optimized) res.sendStatus() Set the response status code and send its string representation as the response body.

21 Handling errors Error handling middleware has 4 parameters instead of usual 3: (err, req, res, next) Error-handling middleware should go last, after other app.use()’s and routing calls Several error-handling middleware functions can be combined to carry out different tasks logging and response generations handle different errors next(err) should be used to pass control from one error handler to the next If you put next(err) to your last error handler, the control will pass to the express default error handler If you want to throw an error yourself in your other middleware, you can use next(err) as well – the error handler will catch it

22 Handling errors express = require('express'); var app = express();
app.get("/login", function(req, res) { var userid = req.query.userid; if (!userid){ next(new Error("userid not found")); } else { // do stuff } }); app.use(function (err, req, res, next) { console.error(err.stack); next(err); if (req.xhr) { // ajax call res.status(500).send('AJAX failed!'); } else { } res.status(500).send('Something failed!'); app.listen(8081); Handling errors

23 Web template engines A web template engine process template files and external data to produce HTMLK pages or their fragments Instead of writing HTML source of a page, you write a template in predefined simple language that is later used to generate a page Express supports several template engines: ejs, handlebars, pug, jade, etc. Example: <!DOCTYPE html> <html> <head> <title>Jade Page</title> </head> <body> <h1>This page is produced by Jade</h1> <p>some paragraph here..</p> </body> </html> doctype html html head title Jade Page body h1 This page is produced by Jade p some paragraph here..


Download ppt "Web-Technology Lecture 11."

Similar presentations


Ads by Google