In this blog we will see how to perform cross origin calls to HANA XSJS APIs or simple terms calling our API from a different application.
Lets first understand what is CORS:
As per [link] Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. Although we can disable CORS for our testing using the keyword --disable-web-securityon our chrome browser, for a productive scenario it is required to enable cross origin access in a more restrictive manner if the APIs are from different origin.
The example below exactly demonstrates how we can achieve cross origin calls to HANA XSJS APIs this.
We have a xsjs service developed which we are calling using the the ajax call in our UI5 or AngularJS Frontend.
Things are working fine for same origin calls. Now lets try calling the ajax call from a different application. For our test scenario let us consider stackoverflow. On calling the ajax call we get the CORS error:
“Access to XMLHttpRequest at 'https://xxxx.hana.ondemand.com/com/xs/xsjs/corsTest.xsjs?_=1573139856' from origin 'https://stackoverflow.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.”
Lets check at the Network tab, we see that the method is changed from GET to OPTIONS:
The request headers show “cross-site” and Origin as “https://stackoverflow.com”
Now to allow access for our xsjs for cross domain we need to add the below details in our .xsaccess file: