permalink |
---|
README.html |
- install Git.
- install Node.js (comes with node package manager).
- Keep your favourite IDE ready, I like to use visual studio code for JavaScript developments.
- Open terminal/cmd/git bash
- Run the command
git clone https://github.com/acucciniello/xhr-post-example.git
- Go to the project
cd xhr-post-example
- Run the server
node server.js
- Realise you are missing the dependency and install the dependency by running
npm install express
- Perform step 4
- Open your browser and visit
http://localhost:3000
- Open developer console by hitting
F12
- Check the Network tab
- Hit the send button on the webpage
- Read the message on the console
- Pat yourself
- Update the AJAX request so that it sends a
GET
request to"http://www2.macs.hw.ac.uk:8080/demo/spellhelp.jsp?prefix=" + value
(value is what we enter in textbox) - Try sending the request now and check your developer console, under the console tab, you should be getting an error. Realise that the server is trying to make a cross domain request to
http://www2.macs.hw.ac.uk:8080
fromhttp://localhost:3000
which is not allowed. It's like going to McDonalds and ordering KFC. - Good thing our server supports CORS (Cross-Origin Resource Sharing), update the url
"http://www2.macs.hw.ac.uk:8080/demo/spellhelp.jsp?prefix=" + value + "&CORS"
, the server is configured so that whenCORS
query parameter is passed it will send an additional headerAccess-Control-Allow-Origin : *
. This header will tell the browser to relax the security and continue the request. In real life you have to tell the guy who manages the server for your website to send these headers if it's trying to make cross domain requests. - (OPTIONAL) You can check how CORS can be enabled on server https://enable-cors.org/server.html
- Update the AJAX request again so that it sends a
GET
request to"http://www2.macs.hw.ac.uk:8080/demo/getScript.jsp?user=imcc&fn=callback"
. - Try sending this request now and expect failure.
- Open a new tab/window on your browser and visit this URL http://www2.macs.hw.ac.uk:8080/demo/getScript.jsp?user=imcc&fn=callback
- Realise the response from the server is in JSONP, i.e. JSON with padding, the method it will invoke is
callback
.
// Normal JSON
{"foo" : "bar"}
// JSONP
callback({"foo" : "bar"})
- Add a new JavaScript function called
callback
that will take a parameter calleddata
and log it on the console. - Update the
send
function to dynamically generate ascript
tag (given below) instead of usingXHR
.
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://www2.macs.hw.ac.uk:8080/demo/getScript.jsp?user=imcc&fn=callback";
document.head.appendChild(s);
- Run the request again and celebrate success.
- (OPTIONAL) This website will explain from a different prespective what we just did https://medium.freecodecamp.org/use-jsonp-and-other-alternatives-to-bypass-the-same-origin-policy-17114a5f2016