16-ServerCom
16-ServerCom
communication
● Response is JavaScript
eval(xhr.responseText);
JSON.parse(xhr.responseText);
Fetching models with XMLHttpRequest
● Controller needs to communicate in the request what model is needed
● Can encode model selection information in request in:
● Popular: Axios - Promise based HTTP client for the browser and node.js
○ Wrapper around XMLHttpRequest
● Similar patterns for REST Update (PUT) and REST Delete (DELETE)
Axios handling of HTTP responses
result = axios.get(URL); // Note: no callback specified! It's a
Promise
result.then((response) => {
// response.status - HTTP response status (e.g. 200)
// response.statusText - HTTP response status text (e.g. OK)
// response.data - Response body object (JSON parsed)
})
.catch((err) => {
// err.response.{status, data, headers) - Non-2xxx
status
// if !err.response - No reply, can look at err.request
});
Promises
Callbacks have haters - out of order execution
fs.ReadFile(fileName, function (error, fileData)
{ console.log("Got error", error, "Data",
fileData);
});
console.log("Finished reading file");
doSomething(args, doneCallback);
completes
axios.get(url).then(function(response) {
var ok = (response.status === 200);
doneCallback(ok ? response.data :
undefined);
}, function(response) {
doneCallback(undefined
);
});
Promises
var myFile = myReadFile(fileName);
var tempData1 = myFile.then(function
(fileData) { return
doSomethingOnData(fileData);
});
var finalData = tempData1.then(function
(tempData2) { return
finalizeData(tempData2);
});
return finalData;
● Note no Pyramid of Doom
● Every variable is a promise
○
Chaining promises
return myReadFile(fileName)
.then(function (fileData) { return
doSomethingOnData(fileData); })
.then(function (data) { return finalizeData(data); })
.catch(errorHandlingFunc);
return myReadFile(fileName)
.then((fileData) => doSomethingOnData(fileData))
.then((data) => finalizeData(data))
.catch(errorHandlingFunc);
Going all in on promises
function doIt(fileName) {
let file = ReadFile(fileName);
let data = doSomethingOnData(file);
let moreData =
doSomethingMoreOnData(data); return
finalizeData(moreData);
}
socket.onmessage = function
(event)
{ JSON.parse(event.data);
Remote Procedure Call (RPC)
● Traditional distributed computation technology supporting calling of a function
on a remote machine.
○ Browser packages function's arguments into a message to the web server.
○ Function is invoked with the arguments on the server.
○ Function's return value is sent back to the browser.