Cross Domain JavaScript calls using JSONP or CORS
Finally I found some solutions after researching and going through all the other posts. I am writing answers for both the approaches.
1. Using JSONP only without CORS:
If using JSONP, there is always a need to make server side change to get json response with acallback
method. Also thecallback
method must be present in thejavascript
to execute. So in the below example, when we call the destination url, if we get the response asmyCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
, then we must have ajavascript method
with the namemyCallBackMethod
. Using jsonp,cookies can also be shared across domains
- in this approach, no need to set any headers in the response by the destination server to allow the requested domains.
- The
callback
method used in this example ismyCallBackMethod
. This name can be anything, except the names injavascript
and theresponse jsonp string must match
client / javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'jsonp',
jsonpCallback: 'myCallBackMethod',
async: false, // this is by default false, so not need to mention
crossDomain: true // tell the browser to allow cross domain calls.
// success: successResopnse, jsonpCallback will call the successCallback
// error: failureFunction jsonp does not support errorCallback. So cannot use this
});
}
window.myCallBackMethod = function(data) {
successResponse(data);
}
successResponse = function(data) {
//functionality goes here;
}
// the json response from the server when calling the url must be in the below format only.
myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
2. Using CORS only without JSONP and WITHOUT URL REWRITES:
If using CORS, there is always aneed to make changes on server and client/javascript
. In this approach,no need to get any callback
method as part of json response. Responsemust be a pure json
. However, make appropriate code changes on the destination server to let the requests pass through. So need to set theheader
in theresponse
object.
Client / javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain.
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
On server, add the below header.
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Here need to give the origin url (the url in the address bar of the page which is making request). Using * means allow any value
- However, with the above code added to server, there wont be any cookies shared between the server and the requested page. To also get the cookies across the requested page and server, we need to add the following properties on client and server.
On client / javascript:
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
}
On server:
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
- These changes allows the client and server to share the cookies.
- However, if using header
Access-Control-Allow-Credentials
in response, there is a restriction on the value for the headerAccess-Control-Allow-Origin
. It shouldnever be * if we want to use Access-Control-Allow-Credentials header
. Hence give exact domain name.
Update on server:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com"); // Give the origin url (the url in the address bar of the page which is making request).
final client / javascript: (CORS only approach)
function makeTheCall(queryString) {
var destinationUrl = www.otherdestinationserver.com;
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
},
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
Final Server code: (CORS only approach)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");
3. Using CORS only WITH A URL REWRITE FILTER setting RESPONSE HEADERS:
If the application is using a url rewrite filter, (mostly all the web applications does), this would give much easier implementation. Instead of following the Final Server code: (CORS only approach) in the approach 2 above, follow the below url to change at xml ( url rewrite filter).
Same code pasted below for quick reference.
<rule enabled="true" match-type="regex">
<name>Enabling CORS Headers</name>
<from>^/path/someMorePath.*$</from>
<condition name="origin" operator="equal">([a-z]+)</condition>
<set type="response-header" name="Access-Control-Allow-Origin">%1</set>
<set type="response-header" name="Access-Control-Allow-Credentials">true</set>
Related videos on Youtube
Venu
Updated on September 15, 2022Comments
-
Venu over 1 year
How to implement cross domain ajax calls on web pages using jsonp and CORS in both the client and the server.
For example, on
www.mytestsite.com
, to make an ajax call towww.otherdestinationserver.com
, how to achieve either usingJSONP
orCORS
implementation?-
charlietfl about 7 yearsPlease be a lot more specific. You want to implement this on your server , or access other remote api's?
-
-
ivosh about 3 yearsThe third solution (where value of Access-Control-Allow-Origin is set to the value of Origin) basically flushes the CORS protection down the toilet. It is equivalent to Access-Control-Allow-Origin: *. You have to explicitly list the allowed domains here, not take them dynamically from the request.