Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCI 3100 Tutorial 5 Web Development Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1.

Similar presentations


Presentation on theme: "CSCI 3100 Tutorial 5 Web Development Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1."— Presentation transcript:

1 CSCI 3100 Tutorial 5 Web Development Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1

2 Outline Introduction to Web Development Socket Http Express Framework Database in Node.js 2

3 Access to a website 3

4 Where is my code? 4

5 OSI Model 5 Application Presentation Session Transport Network Layer Data Link Layer Physical Layer

6 Socket :80 : Index of Process Local PC: localhost

7 Transmission Control Protocol (TCP) var net = require("net"); var server = net.createServer({ allowHalfOpen: false }, function(socket) { // handle connection socket.end("Hello and Goodbye!\n"); }); server.listen(8000, " "); server.on("listensing", function() { console.log("Server :"); console.log(server.address()); }); 7 Get “Net” Module Register the address and port Add an event listener

8 Demo of TCP Connection $ telnet localhost 8000 Trying Connected to localhost. Escape character is '^]'. Hello and Goodbye! Connection closed by foreign host. 8

9 User Datagram Protocol (UDP) var dgram = require("dgram"); var socket = dgram.createSocket("udp4", function(msg, rinfo) { console.log("received " + rinfo.size + " bytes"); console.log("from " + rinfo.address + ":" + rinfo.port); console.log("message is: " + msg.toString()); }); server.bind(8000, function() { console.log("bound to "); console.log(server.address()); }); 9 Get “dgram” module

10 Sending Data via UDP var dgram = require("dgram"); var client = dgram.createSocket("udp4"); var message = new Buffer("Hello UDP"); client.send(message, 0, message.length, 8000, " ", function(error, bytes) { if (error) { console.error("An error occurred while sending"); } else { console.log("Successfully sent " + bytes + " bytes"); } client.close(); }); 10

11 HyperText Transfer Protocol (HTTP) Higher layer than TCP and UDP var http = require("http"); var server = http.createServer(function(request, response) { response.write("Hello HTTP !"); response.end(); }); server.listen(8000); 11

12 Demo of Accessing a HTTP server $ telnet localhost 8000 Trying Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 Host: localhost:8000 HTTP/ OK Date: Sun, 21 Jul :14:26 GMT Connection: keep-alive Transfer-Encoding: chunked 1c Hello HTTP ! 0 12 Header Body

13 Request Method GETA GET request should not alter the state of the server, and is essentially a read operation. POSTPOSTrequests are the submission of HTML forms and the addition of data to a database. HEADRetrieves the same data as an equivalent GETrequest, except the response body should be omitted. PUTPUTs are used to update existing resources on the server. DELETEUsed to delete a resource from a server. CONNECTUsed to create a tunnel through a proxy server. 13

14 Get the Info of Incoming Connection var http = require("http"); var server = http.createServer(function(request, response) { var requestLine = request.method + " " + request.url + " HTTP/" + request.httpVersion; console.log(requestLine); response.end(); }); server.listen(8000); 14

15 Request Header AcceptSpecifies the Content-Types that the client is willing to accept for this request. Accept- Encoding Provides a list of acceptable encodings CookieSmall pieces of data that the server stores on the client Content- Length The length of the request body in octets. HostThe domain and port of the server User-AgentA string identifying the type of client 15 var http = require("http"); http.createServer(function(request, response) { console.log(request.headers); response.end(); }).listen(8000);

16 Response Code OKIndicates that the HTTP request was handled successfully 201CreatedIndicates that the request has been fulfilled, and a new resource has been created on the server 301Moved Perman ently The requested resource has permanently moved to a new URL 400Bad Request Indicates that the request was malformed and could not be understood. 404Not Found The server could not locate the requested URL 500Internal Server Error The server encountered an error while attempting to fulfill the request

17 Demo of Response Code var http = require("http"); http.createServer(function(request, response) { if (request.url === "/foo") { response.end("Hello HTTP "); } else { response.statusCode = 404; response.end(); } }).listen(8000); 17

18 Response Header Cache-ControlSpecifies whether a resource can be cached Content-TypeSpecifies the MIME type of the response body WWW-AuthenticateIf an authentication scheme is implemented for a given resource, this header is used to identify the scheme Content-EncodingSpecifies the encoding used on the data 18 var http = require("http"); var server = http.createServer(function(request, response) { response.setHeader("Content-Type", "text/html"); response.write("Hello HTTP !"); response.end(); }); server.listen(8000);

19 Demo of Request and Response 19

20 Multiple Resources var http = require("http"); http.createServer(function(request, response) { if (request.url === "/" && request.method === "GET") { response.writeHead(200, { "Content-Type": "text/html" }); response.end("Hello home page "); } else if (request.url === "/bar" && request.method === "GET") { response.writeHead(200, { "Content-Type": "text/html" }); response.end("Hello bar "); } else { response.writeHead(404, { "Content-Type": "text/html" }); response.end("404 Not Found"); } }).listen(8000); 20

21 EXPRESS FRAMEWORK 21

22 A Simpler Solution var express = require("express"); var http = require("http"); var app = express(); app.get("/", function(req, res, next) { res.send("Hello home page "); }); app.get("/bar", function(req, res, next) { res.send("Hello bar "); }); http.createServer(app).listen(8000); 22

23 Route Parameter var express = require("express"); var http = require("http"); var app = express(); app.get(/\/products\/([^\/]+)\/?$/, function(req, res, next) { res.send("Requested " + req.params[0]); }); http.createServer(app).listen(8000); 23

24 Route with Named Parameter var express = require("express"); var http = require("http"); var app = express(); app.get("/products/:productId", function(req, res, next) { res.send("Requested " + req.params.productId); }); http.createServer(app).listen(8000); 24

25 Creating an Express Framework Installation: – $npm install -g express Create: – $ express testapp Install dependency: – cd testapp && npm install 25

26 DATABASE IN NODE.JS 26

27 Review on MySQL CREATE TABLE Person ( SSN CHAR(11) NOT NULL, LastName VARCHAR(50) NOT NULL, FirstName VARCHAR(50) NOT NULL, Gender CHAR(1), City VARCHAR(50) NOT NULL, State CHAR(2) NOT NULL, PRIMARY KEY(SSN) ); 27

28 Create Connection var mysql = require("mysql"); var connection = mysql.createConnection({ "host": "localhost", "port": 3306, "user": "username", "password": "secret", "database": "dbname" }); 28 $npm install mysql

29 Query var sql = "SELECT * FROM Person"; connection.query(sql, function(error, results) { if (error) { return console.error(error); } console.log(results); connection.release( ); }); 29

30 THANKS! 30


Download ppt "CSCI 3100 Tutorial 5 Web Development Presented by SU Yuxin Department of Computer Science and Engineering The Chinese University of Hong Kong 1."

Similar presentations


Ads by Google