Solution for Cross Domain request to consume API in SAP Cloud Platform
- Approach 1: Cross-Origin Resource Sharing
- Approach 2: JSONP
- Approach 3: Develop a ProxyServlet
- Further Reading
Recently Jerry is working on a POC: expose ABAP On-Premise function module STFC_CONNECTION via SAP Cloud Platform plus SAP Cloud Connector and consume it via Wechat app in my mobile phone.
The logic of this function module is simple: simply copy the value of importing parameter REQUTEXT to exporting parameter ECHOTEXT.
Detail steps could be found from my blog Use SAP Cloud Connector + SAP Cloud Platform + Java to consume function in ABAP On-Premise system
Deploy it to SAP Cloud Platform, and consume it via the following endpoint:
And then consume it in my Wechat message server. Since it is a POC, I simply hard code the endpoint in line 3:
The expected error message is raised: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
How to resolve it?
Approach 1: Cross-Origin Resource Sharing
If we are allowed to manipulate server response via programming or configuration, we can then leveraging Cross-Origin Resource Sharing by adding header field Access-Control-Allow-Origin in HTTP response. The field value is set according to actual business requirement, acting as a white list.
Detail of this approach could be found from my blog Cross domain request in ABAP and Java
By the way, in SAP Cloud Platform Mobile Service for Development and Operations cockpit there is available settings for Cross Domain Access. However since my POC does not ultilize SAP Cloud Platform Mobile Service, this setting does not help.
Approach 2: JSONP
Just the same as approach 1, some server side development is also needed. Solution detail:
Unfortunately in my use case, it is not possible for me to directly manipulate the HTTP response headers. As a result this approach does not help either.
Approach 3: Develop a ProxyServlet
More detail of such Servlet could be found from my blog Explore the com.sap.ui5.resource.ResourceServlet
So now we can start to develop our own Proxy Servlet. The source code of the whole Java web project could be found from my github.
Below are some keypoints:
1. In index.html the AJAX request is actually sent to ProxyServlet: pay attention to the proxy fragment in request url in line 3 below:
2. Develop a ProxyServlet to intercept those requests whose url contain “proxy”. Then use Java code to consume API hosted in SAP Cloud Platform:
Test and it works as expected: the HTTP request sent from localhost domain could consume the API in SCP.
- Use SAP Cloud Connector + SAP Cloud Platform + Java to consume function in ABAP On-Premise system
- Use JDBC to connect to HANA database instance in SAP Cloud Platform
- Step by step to consume SAP Leonardo Machine Learning API via Java SDK
- Wechat development series 1 – setup your development environment