Asynchronous JavaScript and XML - Yash-777/LearnJava GitHub Wiki

Javascript to make a CROS Domain XHR call:

XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment.

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser.

https://mdn.mozillademos.org/files/14295/CORS_principle.png
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/cors_principle.png

Creating the XMLHttpRequest object Client | Browser Example::

Request headers

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers
var method = GET;
var url = "https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS";

var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('X-PINGOTHER', 'pingpong');
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

var form_urlencoded =  encodeURIComponent("Sensitive Information");
xhr.send("queryParamUserData="+form_urlencoded+
			"&queryParamDate="+ new Date() );
			
xhr.onreadystatechange = function() {
	// xhr.onload = function() {} When the request has successfully completed.
	if (xhr.readyState == 4 && xhr.status == 200) { 
		var responseText = xhr.responseText;
		console.log(responseText);
		
		// process the response.
	}
}

JAVA Response headers:

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send.

https://www.html5rocks.com/static/images/cors_flow.png

CORS support

Server Example:

Response headers

private void addCorsHeader(HttpServletResponse response) {
	// An Access-Control-Allow-Origin (ACAO) header with a wild-card that allows all domains:
	response.addHeader("Access-Control-Allow-Origin", "*");
	//CORS also supports other types of HTTP requests [ GET, POST, PUT, DELETE, OPTIONS, HEAD ]
	response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
	// The list of non-standard | custom HTTP headers.
	response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
	// Tell client that this Pre-flight info is valid for 86400 seconds is 24 hours.
	response.addHeader("Access-Control-Max-Age", "86400");
}

public void sendResponse( String text ) {
    PrintWriter pw = response.getWriter();
    pw.print( text );
}
https://mdn.mozillademos.org/files/14289/prelight.png
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/preflight_correct.png

CORS support Client & Server