Web-Technology Lecture 11.

Slides:



Advertisements
Similar presentations
© 2014 IBM Corporation Empowering the IBM ecosystem Introduction to Developing applications using node.js on Bluemix IBM Ecosystem Development Instructors.
Advertisements

INTRO TO MAKING A WEBSITE Mark Zhang.  HTML  CSS  Javascript  PHP  MySQL  …That’s a lot of stuff!
RESTful Web Development With Nodejs and Express. REST Stands for REpresentational State Transfer Has the following constraints: ◦Client-Server ◦Stateless.
Web server and web browser It’s a take and give policy in between client and server through HTTP(Hyper Text Transport Protocol) Server takes a request.
Server-side Scripting Powering the webs favourite services.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
02 | Introduction to Express Stacey Mulcahy | Technical Evangelist Rami Sayar | Technical Evangelist.
02 | Introduction to Express Framework Stacey Mulcahy | Technical Evangelist Rami Sayar | Technical Evangelist.
Node.Js 1. 2 Contents About Node.Js Web requirement latest trends Introduction Simple web server creation in Node.Js Dynamic Web pages Dynamic web page.
AJAX and REST. Slide 2 What is AJAX? It’s an acronym for Asynchronous JavaScript and XML Although requests need not be asynchronous It’s not really a.
Text INTRODUCTION TO ASP.NET. InterComm Campaign Guidelines CONFIDENTIAL Simply Server side language Simplified page development model Modular, well-factored,
AJAX CS456 Fall Examples Where is AJAX used? Why do we care?
Node.JS introduction. What is Node.JS? v8 JavaScript runtime Event driven Non-blocking standard libraries Most APIs speak streams Provides a package manager.
Introduction to Node.js® Jitendra Kumar Patel Saturday, January 31, 2015.
National College of Science & Information Technology.
Jim Fawcett CSE686 – Internet Programming Spring 2014
Introduction to MEAN (JavaScript Full Stack Development)
NodeJS and MEAN cs6320.
NodeJS.
Tiny http client and server
Objective % Select and utilize tools to design and develop websites.
Web-Technology Exam preparation.
Jim Fawcett CSE686 – Internet Programming Spring 2012
Node.js Express Web Applications
z/Ware 2.0 Technical Overview
Data Virtualization Tutorial… CORS and CIS
Play Framework: Introduction
Play Framework: Introduction
Node.js Express Web Services
Express with Node L. Grewe.
AJAX and REST.
NodeJS and MEAN Prof. L. Grewe.
3 Things Everyone Knows About Node JS That You Don't
CMPE 280 Web UI Design and Development October 24 Class Meeting
CMPE 280 Web UI Design and Development October 26 Class Meeting
Objective % Select and utilize tools to design and develop websites.
PHP / MySQL Introduction
Build Better Apps with MEAN.
CMPE 280 Web UI Design and Development January 30 Class Meeting
Week 04 (Final Project) Node.js Week 04 (Final Project)
Express with Node L. Grewe. Feature 1 Project structure.
Web-Technology Lecture 9.
Testing REST IPA using POSTMAN
WEB API.
CS 174: Server-Side Web Programming January 29 Class Meeting
Web-Technology Lecture 10.
CMPE 280 Web UI Design and Development January 30 Class Meeting
Abel Sanchez, John R. Williams
JavaScript & jQuery AJAX.
CMPE 280 Web UI Design and Development January 29 Class Meeting
Web Programming Language
Lecture 17: Web Service and post
Lecture 16: Writing Your Own Web Service
Chengyu Sun California State University, Los Angeles
RESTful Web Services.
Back end Development CS Programming Languages for Web Applications

Lecture 12: The Fetch Api and AJAx
CSc 337 Lecture 1: post.
Lecture 14: JSON and Web SERVICES
Week 04 Node.js Week 04
Week 05 Node.js Week 05
Chengyu Sun California State University, Los Angeles
Building Apps in Azure with only Scripting Skills
CSc 337 Lecture 18: post.
Chengyu Sun California State University, Los Angeles
Back end Development CS Programming Languages for Web Applications
Lecture 15: Writing Your Own Web Service
Web Application Development Using PHP
CMPE 280 Web UI Design and Development August 27 Class Meeting
Presentation transcript:

Web-Technology Lecture 11

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

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

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

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

Express framework

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 http://expressjs.com 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 :)

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:

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

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

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

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

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')

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!"); });

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: http://localhost:8081/users/3/products/7 http://localhost:8081/users/9/products/2 http://localhost:8081/users/AAA/products/BBB app.get("/users/:userid/products/:productid", function(req, res) { var userId = parseInt(req.params.userid, 10); var productId = parseInt(req.params.productid, 10); // … });

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); })

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: http:// 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: http://localhost:8081/ var express = require("express"); var path = require("path"); var app = express(); var staticPath = path.join(__dirname, "static"); app.use(express.static(staticPath));

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;

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')

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.

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

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

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