Contemporary Web Development Lesson 6
Total Page:16
File Type:pdf, Size:1020Kb
Contemporary Web Development Lesson 6 https://www.youtube.com/watch?v=vUgyG CDa!s "ork async$spaceh%p &tep %nto the server s%de Up until now we've been using the Webpack development server. It can only serve files, we couldn't perform any asynchronous web requests. ...or Express is a highly modular server/routing framework for Node JS. It's most powerful feature is the "middleware" system. &,(* -)ormerly #nown as &%mple ,b.ect (ccess *rotocol) &,(*$over$UD*012 &,(* 3essage 4ransm%ssion ,pt%m%5at%on 3echan%sm W&$6ot%)%cat%on W&$7ase6ot%)%cat%on W&$4op%cs ( standar' )or resource access: W&$7ro#ere'6ot%)%cat%on W&$(''ress%ng W&$4ransfer W&$8vent%ng W&$8numerat%on W&$3a#eConnect%on &ome (*I h%story 3eta'ata 89change Spec%)%cat%on :&,6$W&* W&$*olicy W&$*olicy(ssert%ons W&$*olicy(ttachment W&$D%scovery W&$+nspect%on W&$3eta'ata89change Un%versal Descr%pt%on D%scovery an' +ntegrat%on -UDD+/ WSDL ;.< Core WSDL ;.< &,(* 7%n'%ng Web Serv%ces Semant%cs -W&DL$&/ W&$=esource "ramewor# -W&="/ Secur%ty Spec%)%cat%on W&$Secur%ty >3L &%gnature >3L 8ncrypt%on >3L ?ey 3anagement ->?3&/ W&$SecureConversat%on W&$Secur%ty*olicy W&$4rust W&$"e'erat%on W&$"e'erat%on (ct%ve =e@uestor *ro)%le W&$"e'erat%on *assive =e@uestor *ro)%le Web Serv%ces Secur%ty ?erberos 7%n'%ng Web &%ngle &%gn$,n +nteroperab%lity *ro)%le Web &%ngle &%gn$,n 3eta'ata 89change *rotocol Secur%ty (ssert%on 3ar#up Language -&(3L/ >(C3L We needed a standard so software vendors could open up their services as APIs. SOAP was overly bloated, required WSDL definition protocol, started branching into all kinds of enhancement specifications. =8&4 89ample: 4w%tterAs (*+ REST stands for "Representational State Transfer" From Roy Fielding's doctoral dissertation from 2000. Slowly started getting adopted by tech companies such as Flickr and Amazon. I saw it get popularized after DHH started pushing it. Now is basically everywhere. The idea is to use simple HTTP methods and a naming standard for accessing resources. Just like the simple HTTP GET I did in the first lesson, the GET can be replaced by PUT/POST/DELETE REST is complemented by CRUD, a standard for updating resources. Any action could be defined as one of the following operations on a specified resource path. Install%ng 8xpress and us%ng w%th Babel/ES6 B/ Can start by )or#%ng the async-spaceship pro.ect. ;/ We need to separate cl%ent )rom server. B/ C mv src cl%ent ;/ C m#'%r server 1/ Up'ate the webpack entry 1/ C npm %nstall $$save e9press D/ Create server/%n'e9..s E/ C npm %nstall $$save$'ev Fbabel/node 6/ Change start comman' to Gbabel$no'e server/%n'e9..sG %n paca#ge..son H/ We need a .babelrc )%le where babel$no'e can rea' %ts con)%gurationI =egar'%ng &tateless/Statefull Webpack is best suited for client environments. Client programs are statefull, refresh resets the state and we don't want that. We should keep Server APIs stateless! Then restarting is not a problem. (''%ng Cl%ent Webpac# support (nd server 6odemon support B/ C npm %nstall $$save$'ev webpac#$'ev$m%''leware ;/ C npm %nstall $$save$'ev webpac#$hot$m%''leware 1/ ('' obscure entry to webpack.con)%g..s D/ Up'ate server/%n'e9..s B/ Cnpm %nstall $$save$'ev no'emon ;/ Up'ate the package..son start scr%pt to: nodemon server/%n'e9..s $$e9ec babel$node 1/ (n' we nee' to con)%gure nodemon %n package..son to not restart on cl%ent changes: GnodemonCon)%g": J G%gnoreG: 0Gcl%ent/KG2 L J GspaceshipG : J GenginesG: 0 ● 0 2 $ (rray J ● GmodelG: G6!(6E?G J L $ ,b.ect/D%ctionary. GpowerG : E<<<I ● G G $ &tr%ng. LI ● 6o @uotes $ number. J ● G999G: yyyy M ?ey: value GmodelG : G6!(66?G ● GpowerG: 6<<< ,ther 'ata types such as L date are normally parsed by 2 the appl%cation )rom str%ng. L L (''%ng a server-s%'e spacesh%p log ./)%le$logger..s ./routes..s %mport fs from AfsA app.post-A/log'I async )unct%on (re@I res) J try J const L,GN"+L8 = Alog.t9tA await "%leLog.wr%teLog( e9port funct%on wr%teLog(te9t) J new Date-/.toLocale&tr%ng() Q G: G Q return new Prom%se--resolveI re.ect/ =O J req.body.te9t Q GRnG )s.appen'"%le(L,GN"+L8I te9tI (err/ =O J /P %f (err) J res.sen'-{status: GsuccessGL/ re.ect-err/P L L catch-err) J else J res.status-E<</.sen'-{ error: err.to&tr%ng() L/P resolve-/P L L L/P L/P L/P L ./%n'e9..s Us%ng Fetch async )unct%on serverLog(te9t) J try J let data = {te9t: te9tLP let response = await )etch(B(&8NURL Q Alog'I J ● We are creating a new log entryI so we use method: A*,&4AI *,&4. body: :&,6.str%ngify-'ata/I ● headers:J Data %s sent an' receive' back as :&,6. AContent$4ypeA: Aappl%cat%on/.sonA ● We catch an T44P error an' '%splay %t on L the console. L/ ● %f -Sresponse.ok) J 4he transaction can be v%ewed on the let body = await response..son-/P G6etwor#G tab %n the 'ev tools. throw new &pace8rror(body.error/P L L catch (err/ J console.warn-G8rror post%ng log to serverGI err/ L L 89erc%se B/ ('' a /nasa/asteroids route to the server wh%ch G84S the Gl%st of (stero%'s based on their closest approach 'ate" )rom 6asa's ,pen(*+ – for the current day only. ;/ ('' an async asteroidCheck() )unct%on to spaceship.js that @uer%es the server an' )a%ls the launch %n case any o) the asteroi's com%ng today are w%th%n less than <.B astronom%cal un%ts away. =un the check at the beg%nn%ng of the launch sequence. 1/ ('' /log/filename route to the server that UPD(4ES the name of the log )%le. 4est %t )rom the cl%ent. =egar'%ng (*I access ● Getting an (*+ #ey to access 6(&(As ,pen(*+ %s pretty easyI however we must never store API keys in the clientI because they can eas%ly be p%cked up by any user. ● 4herefore we Gpro9yG the re@uest )rom the serverI an' that way we can also return 'ata that %s alrea'y )ormatted )or the cl%ent's usage. ● ToweverI we must also never store API keys in gitI so %nstea' of wr%ting them %n the source )%le, we 'e)%ne them only locally as an env%ronment var%able. ● 4o 'ef%ne an (*+ #ey %n the server env%ronmentI before runn%ng the server we run: e9port 6(&(N(*+N?8!=B;1DE6HUV -+n w%n'ows use set %nstead of export/ ● 4henI %n the 6o'e JS server code we can access that #ey us%ng the code: process.env.6(&(N(*+N?8! Use 8&6 4emplate &trings )or construct%ng the 6(&( URL ● ES6 4emplate &tr%ngs allow us to eas%ly construct a str%ng that %nclu'es var%ables. 4hey are recogn%5ed by the ` ` @uotes an' var%ables are %n.ected us%ng XJvarL. "or e9ample: let name = GavnerGP let #ey = GB;1DE6GP let url = `http://avner..s.org?name=XJname}Y#ey=XJ#eyLW ● 4he url woul' appear as: http://avner..s.org?name=avnerY#ey=B;1DE6 4%ps ● +n or'er to use fetch %n 6ode, you w%ll have to: ● npm %nstall –save$'ev node$)etch ● %mport )etch )rom Anode$)etchA ● Getting todayAs 'ate %s 'one us%ng: new Date(/P ● 7ut you w%ll have to )ormat %t )or 6(&(As requ%rements. !ou can 'o %t w%th the bu%lt$ %n )unctions or use a l%brary l%#e moment.js. ● DonAt )orget to always try JL an' catch JLS +) you want to catch, pr%nt someth%ng an' then have the error propagate upI you can always throw %t aga%nS ● Use async/await )or every async operat%onS ● DonAt )orget that when us%ng fetchI aZer let response = await fetch you also nee' to let result = await response.json()! ● 4o eas%ly %terate an array %n ES6I use for (let o"ject of array) { $ ● Contact me %) you have any @uestions. .