Communicating with servers in SPAs:AJAX, XHR, CORS, and Web sockets (Week 8) Flashcards
What is AJAX?
✨✨✨
Asynchronous Javascript and XML.
A set of techniques for accessing web servers from a web page.
Makes it possible to update parts of the web page without reloading the page (update data behind the scene asynchronously).
How do you get data from the server without refreshing the page?
AJAX and XHR.
Fires requests to get data and executes http methods programatically using javascript
What are the problems of events?(6)
❌ reactive (waiting before act)
❌ asynchronous (don’t know when)
❌ dependencies (between assets on page)
❌ system & user (system can initiate event AJAX)
❌ volume (# of events handled)
❌ changeability (SPA events change)
What are some solutions to problems with events?(6)
✔️ handlers
✔️ callbacks
✔️ promises
✔️ reactive programming
✔️ async functions
✔️ generators
Why has REST replaced SOAP?
✨✨✨
✔️ Easier to use
✔️ Accepted through firewalls
SOAP has a very heavy infrastructure
✔️ REST works well with AJAX
What is the difference between AJAX and $.ajax()
AJAX is a library
$.ajax() is a call to the library
20
$(document).ready(function(){
21 $.ajax({
22 type: “GET”,
23 url: “http://results.com/api/xml/competitions.php”,
24 data: “competitor=1195&season=2016”,
25 dataType: “xml”,
26 success: function(xml) {…}
27 });
28 });
What is happening at 20, 22-24, 25, 26
20 - when document is <strong>fully loaded</strong>
22 - GET -request type
23 - this url
24 - data being sent
25 - data type being sent
26 - if successful get, do this
What is the purpose of I/O thread and Main thread?
Allow for simultaneous processes that don’t block
Comment on the architecture of diagram of under the hood of the Chrome browser - See diagram doc - #8
multi process architectures
What do SPAs separate?
data (both client and server) from content and presentation
In terms of getting data from server into SPA, what is the problem/requirement that is needed?
Need some way of performing HTTP requests concurrently to, and independently of, the user interacting with the application on the browser –> Security, usability, etc
What type of threading does JS have?
JS is single threaded
Summarize XHR / AJAX (5)
✨✨✨
1) Execute HTTP methods programmatically, and in the ‘background’ -> But remember that JavaScript is single threaded.
2) Use JavaScript to issue HTTP requests e.g. HTTP GET, HTTP POST etc.
3) Use XMLHttpRequest
(XHR) JavaScript API
–> Raw JavaScript XHR; or
–> Abstraction of XHR e.g. jQuery’s $.ajax() method, Vue.js’ vue-resource (v2, not v3), axios etc.
4) Setup XHR request
5) Execute the request
In terms of XHR/AJAX, when setting up XHR request, what things do you specify?
1) HTTP <strong>request</strong>
–> Method e.g. GET, etc. including ? query parameters
–> Body e.g. what’s in the HTTP body you’re sending (of anything)
2) Expected HTTP <strong>responses</strong>: what data you want back from the server e.g. JSON, XML etc
3) <strong>Callbacks</strong> for handling the range of HTTP response/s
–> e.g. successful | unsuccessful response
Explain the example of raw XHR - see image doc - #9
1) onreadystatechange –> when we receive response, execute anonymous function
2) this.readyState == 4 –> 4 = done
Other magic numbers:
0 = unsent –> open() but not send()
1 = opened –> opened() and send()
3 = loading
3) xhttp.open() and xhttp.send() –> open connection and send
Explain the model in image #10
FINISH EXPLANATION
1) request event from application goes to the demultiplexer
Demultiplexer stores event in <strong>non-blocking way</strong>
2) Once demultiplexer done, handling pushes out to Event Queue
3) If some event present, Event Queue passes to event loop
4)
Benefits of concurrency (5)
- decreasing waiting time.
- decreasing response time.
- increases resource utilzation.
- increases efficiency.
- Allows for non-blocking behaviour
Compare concurrency and parallelism
concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations.
🧠 Concurrency is about <strong>dealing</strong> with lots of things at once.
🤹♀️ Parallelism is about <strong>doing</strong> lots of things at once.
Why is the term ‘XMLHttpRequest (XHR)’ now misleading?
1) Can retrieve data other than XML e.g. JSON
2) Works with other protocols, not just HTTP
3) Doesn’t have to be asynchronous… but should be asynchronous and NOT synchronous
Why is it best use an abstraction rather than raw XHR e.g. jQuery’s $.ajax() or a library such as axios for Vue , or fetch API?
Internet Explorer variants do things differently.
e.g. XDomainRequest in Internet Explore 8 and 9
What are the events (and therefore event handlers) for XHR? (8)
1) onloadstart
2) onprogress
3) onabort
4) onerror
5) onload
6) ontimeout
7) onloadend
8) onreadystatechange –> Legacy; deprecated
What is the fetch API?
<strong>Modern interface that allows you to make HTTP requests to servers from web browsers.</strong>
It uses the Promise to deliver more flexible features to make these requests.</strong>
1) ES6 style JS
2) syntactic sugar for promises
3) Native Javascript API introduced in 2017
Give the fetch API pattern for a basic fetch.
See diagrams doc - #11
Give the fetch API pattern for a basic fetch that uses an async function
See diagrams doc - #12
What does CORS stand for?
Cross Origin Resource Sharing
What is the main purpose of CORS?
✨✨✨
🦀 Request resources from different domains/servers.
🦀 <strong>Defines a way in which a browser and server can interact to determine if it is safe to allow cross origin requests.</strong>
🦀 Uses Http headers and relies on the browser to honour the restrictions.
🦀 Prevents people from drawing lots of info from resources they that aren’t allowed to
Explain the everyday and legitimate cross-origin resource request diagram –> See diagram #13
TODO
1) Browser sends an HTTP request to first.com to retrieve Resource A’s HTML
2) The server retrieves Resource A and delivers it to the browser in an HTTP response
3) The browser then sends another HTTP request to another address second.com to get Resource B’s image
4) The server retrieves this resource and delivers it to the browser in an HTTP response
What is a common practice for many web pages (web applications) to do in terms of loading resources?
Load resources from separate <strong>domains</strong> –> CSS stylesheets, images, frames, video
Explain the cross-origin requests with diagram –> See diagram #14
✨✨✨
If a script wants to get image, gets CORS error as can only make request to originating origin that originally contact i.e. first.com
<strong>For security reasons, browsers restrict [scripts]s in the way they make cross-origin resource requests. By default, an XHR request can be made only to the originating origin (the same origin)</strong>
What is a common practice for many web pages (web applications) to do in terms of loading resources?
Load resources from separate domains CSS stylesheets, images, frames, video
What sorts of “cross-domain” requests are forbidden by the same-origin security policy? Why?
✨✨✨
AJAX/ XHR requests
AJAX requests are JavaScript and [script]s can’t by default make cross-origin requests
What does CORS define?
✨✨✨
a way in which a browser and a server can work together to determine whether or not it is safe to allow a client-side app to make a cross-origin request
What enforces CORS?
Browser
What does the CORS standard describe?
✨✨✨
<strong>HTTP headers</strong> (how to access URLs e.g. permissions) <strong>which provide browsers and servers a way to request remote URLs only when they have permission </strong>
The app can’t access (some of) these headers
In terms of CORS, who has to perform some validation and authorisation?
Server
In terms of CORS, who is generally responsible for supporting the headers and honouring the restrictions they impose?
Browser
Note: not the application’s responsibility; the browser’s responsibility e.g. to prevent the application doing something
In terms of CORS, what defines origin?
Origin is defined in terms of:
1) Protocol
2) Domain
3) Port
If two addresses have the identical { protocol, domain, port}, is it same-origin or cross-origin?
Same origin
If two addresses have the different { protocol, domain, port}, is it same-origin or cross-origin?
Cross-origin
Which of the following are same-origin and cross-origin?
1) http:example.com:80
2) https:example.com:80
3) http:exemple.com:80
4) http:example.com:463
All are cross-origin as have different {protocol, domain, port}
What are HTTP forbidden headers? Give examples.
1) <strong>Some headers are managed by the browser and/or the server, and these headers can’t be manipulated by the client-side application</strong>
2) “A forbidden header name is an HTTP header name that cannot be modified programmatically; specifically, an HTTP request header name.”
3) Examples of forbidden headers ( browser should prevent you from modifying these): <strong> Access-Control-* Access-Control-Origin Access-Control-Headers Origin </strong>
What does ‘Access-Control-Allow-Origin: *’ allow?
Allow the request from any origin
What does ‘Access-Control-Allow-Origin: https://foo.bar’ allow?
Allow the request only from resources originating from HTTPS://foo.bar (remember what defines an origin)
What does ‘Access-Control-Allow- Methods: POST, GET, OPTIONS’ allow?
Allow only these HTTP methods
What does ‘Access-Control- Max-Age: 86400’ allow?
Access is allowed for up to 86400 milliseconds (86.4s)
When is ‘Access-Control- Credentials: true’ required?
Required if you want to send cookies etc
(and can’t use Access-Control-Allow-
Origin: *)
Explain the example diagram of ‘accept request from foo.com only’ - #15
1) make original request to foo.com
2) comes back as a script, has XHR in it
3) XHR executes something that requests origin: https://foo.com
NOTE: browser adds in origin as header
4) makes request
5) response returned
Works for single origin
Explain the example diagram of ‘accept request from anywhere (*)’ - #img 16
1) make original request to foo.com
2) comes back as a script, has XHR in it
3) XHR executes something that requests origin: https://foo.com
NOTE: browser adds in origin as header
4) makes request
5) response returned
Works for any origin e.g. local host
Explain the example diagram of ‘reject request’ - img #17
rejects request as access control origin is boo.com but request is foo.com
So, makes request but browser will not honour it
Browser implements rule i.e. blocks
Explain the example diagram of ‘fooling the server’ - img #18
Fool by writing browser that doesn’t support CORS
Harming user of browser
What does JSON-P refer to?
JSON with padding
Explain JSON-P?
Comment on age, usefulness and security.
- A much older approach to get data, pre-CORS
So may still be useful for old/er browsers that don’t support CORS
- Has security weakness so should use CORS instead
How does JSON-P work?
🦚 Request a [script] from another origin (this is legal)
🦚 Server wraps the data, that you want to get access to, inside the script
🦚 In the app on the client side, you call the function in the [script] and unpack the data
–> Server and app must know beforehand what the function name etc is
–> There is still cooperation needed with server
NOTE: [ = < and ] = >
Compare HTTP AJAX with Web sockets
✨✨✨
<strong>HTTP, AJAX</strong>:
🦧 Uni-directional communication: client makes request, server makes response
🦧 stateless
🦧 Relatively less efficient
🦧 Good for retrieving resources
🦧 Must implement polling to get updates from the server
<strong>Web Sockets</strong>
🐳 Persistent 2-way communication
🐳 Maintains state
🐳 Fast, lightweight and can maintain much higher load of connections
🐳 Good for real-time communication: chats, games, etc.
🐳 Server can push data to client
Compare polling and pushing in terms of HTTP AJAX and web sockets.
✨✨✨
<strong>HTTP AJAX uses polling</strong>
🦧client initiates and says that it wants an update (via a GET) from the server
🦧 poll server then get response from server
<strong>Web sockets use pushing.</strong>
🐳 establish web connection and then server can push data to the client
How are web socket connections made?
✨✨✨
Handshake mechanism
- Client send initial HTTP GET request to the server.
- Server responds with information on how to connect to socket server.
- Client sends HTTP GET with header “Connection: Upgrade” and connection is upgraded to a socket connection.
Is it common for browsers to support web socket API?
Yes, web sockets are now supported in most browsers
How is the web socket API implemented in npm packages?
e.g. ws, socket-io, websocket, and express-ws (express integration with ws)
Some libraries implement fallback (emulates socket connection in http when not supported in browser)
Explain the sample client connection example - image doc #19
TODO
Explain the simple server example - image doc #20
TODO
In terms of the browser process section of the Chrome browser, what does the browser maintain?
See diagram doc - #8
browser maintains main and I/O thread
In terms of the browser process section of the Chrome browser, what does the browser process allow for?
See diagram doc - #8
allow for different things to run side by side without blocking each other
In terms of the browser process section of the Chrome browser, what does the main/UI thread do?
See diagram doc - #8
main/UI thread renders web pages onto screen
In terms of the browser process section of the Chrome browser, what does the I/O thread handle?
See diagram doc - #8
I/O thread handles inter-process communication and network connections (with other servers)
In terms of the render process section of the Chrome browser, what threads does the render process use?
See diagram doc - #8
has render and main threads
In terms of the render process section of the Chrome browser, what component of the render process do the main work? What does it handle?
See diagram doc - #8
RenderProcess is the main work, where it handles inter-process communication events
In terms of the render process section of the Chrome browser, what are the components of the render thread?
See diagram doc - #8
Render thread has the RenderView, WebKit and ResourceDispatcher pieces.
In terms of the render process section of the Chrome browser, what does the ResourceDispatcher ask for?
See diagram doc - #8
resources
In terms of the render process section of the Chrome browser, what does the RenderProcess handle?
See diagram doc - #8
request and response
In terms of the render process section of the Chrome browser, what is WebKit?
See diagram doc - #8
WebKit is rendering engine inside Chrome (constructs DOM and draw web page pieces, V8 engine lives here)
In terms of the Chrome browser, what is the result of the structure overall?
See diagram doc - #8
Means that if one tab fails, others will keep working.
Is it common for modern browsers to implement Fetch API?
Yes