Express - Polito-wa1-aw1-2022.github.io

Transcription

ExpressSERVERA look at the server sideFulvio CornoLuigi De RussisEnrico MasalaApplicazioni Web I - Web Applications I - 2021/2022

Goal Implement a (simple, minimal)web server––––In JavaScriptFor hosting static contentsFor hosting dynamic APIsSupporting persistence in expressjs/express2Applicazioni Web I - Web Applications I - 2021/2022

The Protocol of the WebHTTP3Applicazioni Web I - Web Applications I - 2021/2022

etf.org/html/rfc7231HTTP protocolGET / HTTP/1.1Host: elite.polito.itHTTP/1.0 NT2006.1;OK WOW64; rv:37.0) Gecko/20100101 Firefox/37.0User-Agent: Mozilla/5.0 (WindowsCache-Control: no-store, no-cache, must-revalidate,Accept: text/html,application/xhtml xml,application/xml;q 0.9,*/*;q 0.8Connection: Keep-AliveAccept-Language: it-IT,it;q 0.8,en-US;q 0.5,en;q 0.3Content-Encoding: gzipAccept-Encoding: gzip, deflateContent-Type: text/html; charset utf-8Cookie: utma 50.353;Connection: keep-alive Date: Wed, 08 Apr 2016 13:36:24 GMTExpires: Mon, 1 Jan 2020 00:00:00 GMTKeep-Alive: timeout 15, max 100Last-Modified: Wed, 08 Apr 2016 13:36:24 GMTPragma: no-cacheServer: Apache/2.4.6 (Linux/SUSE)Transfer-Encoding: chunkedX-Powered-By: PHP/5.6.30p3p: CP "NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM« !DOCTYPE html html head . . . . . .Applicazioni Web I - Web Applications I - 2021/20224

HTTP MessagesRequest An initial lineZero or more header linesA blank line (CRLF)An optional message bodyResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse Body5Applicazioni Web I - Web Applications I - 2021/2022

Request – Initial Line A request initial line has three partsseparated by white spaces:RequestResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse Body– Method name– Local path of the requested resource– Version of HTTP being used GET /path/to/file/index.html HTTP/1.06Applicazioni Web I - Web Applications I - 2021/2022

RequestHTTP MethodsGETRequests a representation of the specified resource. Should only retrievedata.HEADAsks for a response identical to GET, but without the response bodyPOSTSubmit an entity to the specified resource, often causing a change instate or side effects on the serverPUTReplaces current representations of the target resource with the requestpayloadDELETEDeletes the specified resourceTRACEMessage loop-back test along the path to the target resourceOPTIONSDescribe the communication options for the target resourceCONNECTEstablish a tunnel to the server identified by the target resourcePATCHApply partial modifications to a resourceResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse 37Applicazioni Web I - Web Applications I - 2021/2022

Response – Initial Line A status line 3 parts separated by spaces:RequestResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse Body– The HTTP version– The response status code– An English phrase describing the status code Example:– HTTP/1.0 200 OK– HTTP/1.0 404 Not Found8Applicazioni Web I - Web Applications I - 2021/2022

Response Status Codes 1xx – Informational2xx – Success3xx – Redirection4xx – Client Error5xx – Server Error 100 Continue101 Switching Protocols200 OK201 Created202 Accepted203 Non-Authoritative Information204 No Content205 Reset Content300 Multiple Choices301 Moved Permanently302 Found303 See Other305 Use Proxy307 Temporary Redirect400 Bad Request402 Payment Required403 Forbidden404 Not Found405 Method Not Allowed406 Not Acceptable408 Request Timeout410 Gone411 Length Required413 Payload Too Large414 URI Too Long415 Unsupported Media Type417 Expectation Failed426 Upgrade Required500 Internal Server Error501 Not Implemented502 Bad Gateway503 Service Unavailable504 Gateway Timeout505 HTTP Version Not SupportedRequestResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse Body9Applicazioni Web I - Web Applications I - 2021/2022

RequestHeader Lines Initial lineheader1: value1header2: value2header3: value3Information about the request/responseInformation about the object sent in the message bodyOne line per headerHeader-Name: header-valueHTTP/1.1 defines 46 headers. Only 1 is mandatory in all requests:Request BodyResponseInitial lineheader1: value1header2: value2header3: value3Response Body– TTP/Headers10Applicazioni Web I - Web Applications I - 2021/2022

RequestMessage Body Data sent after the header lines– Request: data entered in a form, a file to upload, – Response: the resource returned to the clientResponseInitial lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse Body Images text/plain, text/html . Content-Type (header) indicates the media type of the ent-Type:Content-Type:text/html; charset UTF-8application/jsonmultipart/form-data; boundary somethingapplication/x-www-form-urlencoded Content-Encoding: the compression (e.g., gzip) applied to the TTP/Basics of HTTP/MIME types11Applicazioni Web I - Web Applications I - 2021/2022

Body In Different HTTP MethodsMethodRequest BodyResponse BodyIdempotentHTML FormsGETNoYes: resource contentYesYesHEADNoNoYesNoPOSTYes: form data orapplication dataMay (usuallymodification results)NoYesPUTYes: application dataMay (usuallymodification al lineheader1: value1header2: value2header3: value3Initial lineheader1: value1header2: value2header3: value3Request BodyResponse TTP/Methods12Applicazioni Web I - Web Applications I - 2021/2022

The Express Handbook, Flavio /A simple and easy to use HTTP and Application serverEXPRESS13Applicazioni Web I - Web Applications I - 2021/2022

Web Frameworks in Node Node already contains a ‘http’module to activate a web server– Low-level, not very friendly Several other frameworks weredeveloped Express is one of the mostpopular, and quite easy to usenpm initnpm install expressnode index.jshttp://nodeframework.com/14Applicazioni Web I - Web Applications I - 2021/2022

Running the Express Server node index.js Will start the server applicationwith the specified file Until the application crashes, oris interrupted by the user ( C) If you modify a file, it must bestopped and restarted. Useful Tip: nodemon– nodemon executes a script with node,and monitors any changes of the JS files– node is automatically restarted if a fileis modified sudo npm install –g nodemon nodemon index.js15Applicazioni Web I - Web Applications I - 2021/2022

First Steps With Express Calling express() creates anapplication object app app.listen() starts the serveron the specified port (3000) Incoming HTTP requests arerouted to a callback according to– path, e.g., '/'– method, e.g., get Callback receives Request andResponse objects (req, res)// Import packageconst express require('express') ;// Create applicationconst app express() ;// Define routes and web pagesapp.get('/', (req, res) res.send('Hello World!')) ;// Activate serverapp.listen(3000, () console.log('Server ready')) ;16Applicazioni Web I - Web Applications I - 2021/2022

Routing app.method(path, handler);– app: the express instance– method: an HTTP Request method (get, post, put, delete, ) app.all() catches all request types– path: a path on the server Matched with the path in the HTTP Request Message– handler: callback executed when the route is matchedapp.get('/', (req, res) res.send('Hello World!')) ;17Applicazioni Web I - Web Applications I - 2021/2022

Handler Callbacksreq (Request object)function (req, res) { . }res (Response 18Applicazioni Web I - Web Applications I - 2021/2022

Generate an HTTP Response res.send(‘something’) sets the response body and returns it to thebrowser res.end() sends an empty response res.status() sets the response status code– res.status(200).send()– res.status(404).end() res.json() sends an object by serializing it into JSON– res.json({a:3, b:7}) res.download() prompts the user to download (not display) theresource19Applicazioni Web I - Web Applications I - 2021/2022

Redirects res.redirect('/go-there')20Applicazioni Web I - Web Applications I - 2021/2022

Extending express With ‘Middlewares’ Middleware: a function that is called for every request function(req, res, next)– Receives (req,res), may process and modify them– Calls next() to activate the next middleware function Insert a middleware on a specific route– app.method(path, middlewareCallback, (req,res) {}) Register a middleware with– app.use(middlewareCallback)– app.use(path, middlewareCallback)// handles requests in the specified path, only21Applicazioni Web I - Web Applications I - 2021/2022

Serving Static Requests Middleware: express.static(root, [options]) All files under the root are served automatically– No need to register app.get handlers per each atic', express.static('public'));Serves files from ./public localhost:3000/hello.htmlServes files from ./public files.htmlApplicazioni Web I - Web Applications I - 2021/202222

Interpreting Request ParametersRequest methodParametersValues available inGETURL-encoded/login?user fc&pass 123req.querynonereq.query.userreq.query.passPOST / PUTFORM-encoded in the request bodyPOST / PUTJSON stored in the request body{ "user": "fc", "pass": "123" }req.bodyreq.body.userreq.body.passMiddleware azioni Web I - Web Applications I - 2021/2022

PathsPath typeExampleSimple paths (String prefix)app.get('/abcd', (req, res, next) {Path Pattern (Regular expressions)app.get('/abc?d', (req, res, next) {app.get('/ab cd', (req, res, next) {app.get('/ab\*cd', (req, res, next) {app.get('/a(bc)?d', (req, res, next) {JS Regexp objectapp.get(/\/abc \/xyz/, (req, res, next) {Array (more than one path)app.get(['/abcd', '/xyza', /\/lmn \/pqr/],(req, res, next) s24Applicazioni Web I - Web Applications I - 2021/2022

Parametric Paths A Path may contain one or moreparametric segments:––––Using the ‘:id’ syntaxFree matching segmentsBound to an identifierAvailable in req.paramsapp.get('/users/:userId/books/:bookId', (req,res) {res.send(req.params)});Request ts in:req.params.userId "34"req.params.bookId "8989" May specify a matching regexp– /user/:userId([0-9] -parameters25Applicazioni Web I - Web Applications I - 2021/2022

Logging By default, express does not log the received requests For debugging purposes, it is useful to activate a logging middleware Example: morgan– https://github.com/expressjs/morgan (npm install morgan)– const morgan require('morgan');– app.use(morgan('dev'));26Applicazioni Web I - Web Applications I - 2021/2022

Validating Input https://express-validator.github.io/docs/– npm install express-validator Declarative validator for query parametersapp.post('/user’, [// additional (2nd) parameter in app.post to pre-process requestcheck('username').isEmail(), // username must be an emailcheck('password').isLength({ min: 5 }) // password must be at least 5 chars long], (req, res) {const errors validationResult(req);if (!errors.isEmpty()) {return res.status(422).json({ errors: errors.array() });}https://github.com/val. . . Process azioni Web I - Web Applications I - 2021/2022

Other leware.htmlApplicazioni Web I - Web Applications I - 2021/202228

License These slides are distributed under a Creative Commons license “Attribution-NonCommercialShareAlike 4.0 International (CC BY-NC-SA 4.0)”You are free to:– Share — copy and redistribute the material in any medium or format– Adapt — remix, transform, and build upon the material– The licensor cannot revoke these freedoms as long as you follow the license terms. Under the following terms:– Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes weremade. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you oryour use.– NonCommercial — You may not use the material for commercial purposes.– ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributionsunder the same license as the original.– No additional restrictions — You may not apply legal terms or technological measures that legally restrictothers from doing anything the license permits. 29Applicazioni Web I - Web Applications I - 2021/2022

First Steps With Express Calling express()creates an application object app app.listen()starts the server on the specified port (3000) Incoming HTTP requests are routed to a callback according to -path, e.g., '/' -method, e.g., get Callback receives Request and Response objects (req, res) // Import package