AJAX
- AJAX stands for Asynchronous JavaScript and AJAX.
- It refers to JavaScript being able to make network calls in the background and fetch data that can update the web page.
API Server
- A web server can serve raw data instead of HTML.
- Look at the
toys.json
route in expressMVC
. It just returns the raw array of toys.
- Run the server and visit the
/toys.json
route
- Look at developer tools. Notice the content-type of
application/json
- Create new toy and look at network history. (In particular, the post data).
- Any program that can generate a POST request can have the same effect.
- Run
curl -d 'toy[name]=simon&toy[description]=A+memory+game&toy[manufacturer]=Milton+Bradley&toy[price]=20' http://localhost:3000/toys
- (Of course, there are security implications we haven’t discussed yet.)
Calling API server from Client-side JavaScript code.
- Browsers use an object called
XMLHttpRequest
- (sometimes abbreviated
XHR
)
- Originally designed to receive data in XML format
- Browsers will automatically try to parse data as XML.
- JSON format is more common today.
- To use
- The
onreadystatechanged
callback will be called several times, because there are 5 “ready states”.
- Once the data is complete and parsed, it can be used to update the DOM.
POSTing AJAX data
- Open a connection as before
- But, this time, set action to “POST”
- Add call to
setRequestHeader("Content-type", "application/x-www-form-urlencoded");
so the server knows how the data is formatted.
- Pass properly encoded data to the
send
method:
send(encodeURI(postString));
(where postString
contains the data we want to send.)
- Notice that any forwards (e.g., 302 responses) are followed.
Same Origin policy
- By default, browsers follow a Same Origin Policy
- AJAX calls on web pages can only go to the server that served the .html page.
- This is to prevent someone from emailing you a web link and having that page access private data
- Supposed you are logged into your bank
- While logged in you check your email and follow an embedded
- What if that embedded link goes to a web page with JavaScript that tries to access your bank?
- Launch python server in
public
directory. Visit ajax1.html
- Look in console. Notice the error message “has been blocked by CORS policy”
- Remember this is implemented by the Browser to protect the user. The server (at least the server wrote) doesn’t care.
- So, how do we provide a front-end and back-end for Single Page Apps like React?
- Have the back-end serve the bundled front-end code.
- Use CORS
- CORS: Cross Origin Resource Sharing
- There are now special headers that servers can send to tell the browser that a cross-origin request is reasonable/safe.
res.setHeader("Access-Control-Allow-Origin", "*");
will tell every browser that the cross-origin request is OK.
- Don’t ever use “*” in production!
- In fact, it won’t work on a site that uses authentication.
- I added this header “by hand” to the
expressMVC
example. A better solution would have been to use the coors
package. https://expressjs.com/en/resources/middleware/cors.html
AJAX and React
- See
Authors_v6.jsx
- Basic idea:
- Make AJAX call, then have the callback set the authors
- Make sure you use the
useEffect
hook with []
as a second parameter to avoid an infinite loop.
- You can use any AJAX library you like
- A simpler way to send the data for a POST request is to use JSON (instead of the encoded URI)
- Simply make the post body
JSON.stringify
- Must switch to
app.use(bodyParser.json());
in express so the data is parsed correctly.