javascript on the server
play

JavaScript on the Server Niels Olof Bouvin 1 Overview The HTTP - PowerPoint PPT Presentation

JavaScript on the Server Niels Olof Bouvin 1 Overview The HTTP protocol The http module Input and output on the Web The Express framework HTML templates with handlebars Data-driven sites 2 Client/server communication Server resource


  1. JavaScript on the Server Niels Olof Bouvin 1

  2. Overview The HTTP protocol The http module Input and output on the Web The Express framework HTML templates with handlebars Data-driven sites 2

  3. Client/server communication Server resource request resource request Client Client The Web is an example of a client/server architecture clients make requests servers return resources communication is always initiated by the client In the context of the Web, clients are (usually) Web browsers, though they can be anything that speaks http and https http and https are the protocols with which Web clients and servers communicate 3

  4. The Uniform Resource Locator protocol resource fragment server z }| { z }| { z }| { z }| { https : // users − cs . au . dk / bouvin / dBIoTP2PC / 2017 / exam . html # topics Combines protocol the method with which computers communicate, e.g., http, https, ftp, rtp, … with host or server name usually resolved using DNS resource name could just be a fj le name, but could also something more general (we’ll return to this) and fragment identi fj er used to point into a resource—usually a text-based one 4

  5. The HyperText Transfer Protocol At its simplest, a request and response for a resource but in reality, it is a bit more complex and far richer: http://127.0.0.1:8080/hello.txt GET /hello.txt HTTP/1.1 request: Host: 127.0.0.1:8080 User-Agent: curl/7.54.0 (from client) Accept: */* headers explaining what the client wants response: HTTP/1.1 200 OK server: ecstatic-2.2.1 and what the server (from server) last-modified: Tue, 02 Jan 2018 11:54:58 GMT etag: "77865272-13-"2018-01-02T11:54:58.000Z"" delivers cache-control: max-age=3600 content-length: 13 content-type: text/plain; charset=UTF-8 Date: Tue, 02 Jan 2018 12:01:52 GMT Connection: keep-alive (A blank line) the actual resource Hello World! 5

  6. Operating on resources HTTP supports four main methods: GET retrieve the state of a resource — don’t modify it POST create new resource, do not specify identi fj er PUT update existing resource, or create new resource with an identi fj er DELETE remove a resource 6

  7. A selection of HTTP status codes 200 OK Standard response for successful HTTP requests. 201 Created The request has been ful fj lled and resulted in a new resource being created 202 Accepted The request has been accepted, but is not yet ful fj lled 301 Moved Permanently This and all future requests should be directed to the given URI 404 Not Found The requested resource could not be found 500 Internal Server Error The server has experienced an error, and could not ful fj l the request 7

  8. Overview The HTTP protocol The http module Input and output on the Web The Express framework HTML templates with handlebars Data-driven sites 8

  9. What should a Web server do? Receive a Request extract information from the Request’s header and body, such as resource identi fj cation (‘/min/test.txt’), type of operation (GET, PUT, …), acceptable data formats (‘text/html’), etc. Create a Response return a suitable resource for the Request of the appropriate data type and with the correct information in the header This is all 9

  10. Back to Hello World Now that we are starting server programming, we should begin using proper tools and structure in our code that means using NPM to handle the basics, such as starting the program, and keeping track of necessary modules, which is done through the package.json fj le as well as having a systematic approach to folder structure A new project can be initialised with npm init -fy 10

  11. . ├── app ./package.json │ └── index.js ├── index.js └── package.json { "name": "basic-hello-world", "version": "1.0.0", "main": "basic-hello-world.js", "scripts": { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "Niels Olof Bouvin", "license": "ISC", "description": "A simple hello world server" } I have fj lled out a few fj elds, including start and author 11

  12. . ├── app ./index.js │ └── index.js ├── index.js └── package.json 'use strict' require('./app/index') It is considered good coding style to let the central index.js be sparse, and let the actual functionality reside in appropriately named folders and fj les 12

  13. . ├── app ./app/index.js │ └── index.js ├── index.js └── package.json 'use strict' const http = require('http') const port = 3000 let counter = 0 const server = http.createServer((request, response) => { console.log(`request.url=${request.url}`) response.end(`Hello World! times ${counter++}\n`) }) server.listen(port, () => console.log(`Listening on http://localhost:${port}`) ) http.createServer() requires a callback function that gets a request and a response object the request object is read (quite simply, here) and the response object has data added to it, and is fj nalised with .end (), which returns the response to the Web browser but fj rst, the server must be set to listen to incoming requests on a speci fj c port 13

  14. Running the server 14

  15. Taking a closer look 15

  16. . ├── app Adding a bit of HTML style │ └── index.js ├── index.js └── package.json 'use strict' const http = require('http') const port = 3000 let counter = 0 const server = http.createServer((request, response) => { console.log(`request.url=${request.url}`) response.end(`<i>Hello World!</i> times ${counter++}\n`) }) server.listen(port, () => console.log(`Listening on http://localhost:${port}`) ) This should work, right? 16

  17. Probably not as intended 17

  18. . ├── app Correct header info is crucial │ └── index.js ├── index.js └── package.json 'use strict' const http = require('http') const port = 3000 let counter = 0 const server = http.createServer((request, response) => { console.log(`request.url=${request.url}`) response.setHeader('Content-Type', 'text/html') response.end(`<i>Hello World!</i> times ${counter++}\n`) }) server.listen(port, () => console.log(`Listening on http://localhost:${port}`) ) If we do not set an explicit Content-Type using the setHeader() method, the browser will assume it is ‘text/ plain’ , and that is rarely what we want ‘text/html’ is right for HTML documents 18

  19. Taking a closer look again 19

  20. And in the Web browser… 20

  21. Overview The HTTP protocol The http module Input and output on the Web The Express framework HTML templates with handlebars Data-driven sites 21

  22. Input and Output on the Web We have seen several example of getting data from a server to a Web browser But how do you get data from a Web page back to the server? this was solved, in the simplest form, in the early Web around HTML 2.0 There are two basic methods GET POST 22

  23. Input through GET Very simple: http://…/foo.html ?arg1=value&arg2=value&arg3=value (and so on) Advantage you can make links that contain arguments to the server Disadvantage there is a space limitation cannot be used for, e.g., fj le upload you would not want a password to be visible in the browser bar 23

  24. A more speci fj c greeting 'use strict' const http = require('http') const url = require('url') const port = 3000 let counter = 0 let recipient const server = http.createServer((request, response) => { console.log(`request.url=${request.url}`) const query = url.parse(request.url, true).query if ('recipient' in query) { recipient = query['recipient'] } else { recipient = 'World' } response.setHeader('Content-Type', 'text/html') response.end(`<i>Hello ${recipient}!</i> times ${counter++}\n`) }) server.listen(port, () => console.log(`Listening on http://localhost:${port}`) ) The standard Node ‘ url ’ module can parse the query 24

  25. Input through POST Requires a di ff erent HTTP method: POST Data is transferred in the body of the request rather than the URL you can send much more data because this data can be split up across several network packages, it is necessary to assemble the data at the server, before it can be processed the standard Node module ‘ querystring ’ can parse this kind of data The data must be input through a <form> element on a Web page 25

  26. A HTML form <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Greetings for you</title> </head> <body> <form method="POST" action="http://localhost:3000/"> <div> <label for="recipient">Recipient:</label> <input type="text" id="recipient" name="recipient"> </div> <div> <label for="message">Message:</label> <textarea id="message" name="message"></textarea> </div> <div> <button type="submit">Submit</button> </div> </form> </body> </html> A form has a method and an action There are many di ff erent kinds of input types 26

Recommend


More recommend