CSSE280: Connect Front-end to REST API
Connect the pieces together
Checkout contacts-app-frontend project from your Git repo
By the end of this unit you should be able to...
Same-origin policy
Same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.
It is a critical security mechanism for isolating potentially malicious documents.
Origin definition:
Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.
Same origin or not?
Consider the URL http://store.company.com/dir/page.html:
Do the following URLs have the same origin? Why?
AJAX works with same-origin
Ajax works smoothly with data from the same origin
For security reasons, browsers do not load Ajax responses from other domains (a.k.a cross-domain requests)
Workarounds:
Next workaround
CORS approach
CORS ⇒ Cross-Origin Resource Sharing
Every time a browser and server communicate, they share information with each other using HTTP headers
CORS involves adding extra information to the HTTP headers to let the browser and server know that they should communicate with each other
CORS is
Enabling CORS on back end server
Since CORS must be enabled on the API server, we must enable it in our application back end.
prompt> cd contacts-app-backend-with-middleware
prompt> npm install cors --save
In app.js, we must require and use cors before routing requests.
const cors = require('cors');
…..
app.use(cors());
Connect front end with back end using Ajax
Front end application is in project contacts-app-frontend. Code below (and in main.js) gets all contacts and display them in index.html
$.ajax({
url: apiUrl, // URL to /contacts/ path on REST API server
type: 'GET',
dataType: 'JSON',
success: (data) => {
if (data) {
displayContacts(data);
} else {
console.log("Contact not Found");
}
},
error: (request, status, error) => {
console.log(error, status, request);
}
});
Sharing data between pages of a website
Browser has localStorage and sessionStorage that can be used to do so.
localStorage never expires
sessionStorage expires when browser closes
Their APIs are similar
// Saving to sessionStorage
const contactToUpdateString = JSON.stringify(contactToUpdate);
sessionStorage.setItem("contactToUpdate", contactToUpdateString);
// Reading from sessionStorage
const contactToUpdateString = sessionStorage.getItem("contactToUpdate");
const contact = JSON.parse(contactToUpdateString);
TODO
Complete front-end application to:
Update a single contact
Create a new contact
Delete a single contact
Take your time, study the code:
Add logging to see what is happening when things happen
(Use “debugger;” to freeze the code and see what variable values are on)