We recently released the OCC Web Services – Omni Commerce Web Services – which are RESTful Web Services for the key commerce functionality of the hybris platform. While calling these web services from a mobile client or other system like a POS terminal is no problem, as the REST calls are done from native code, I figured out a pure HTML5/CSS3/JavaScript frontend would have issues due to the same origin policy: you cannot simply do AJAX requests to different machines other than the one the HTML page was served from. If you were running such a pure HMTL5/CSS3/JavaScript solution on the same host as the API, there is little sense in doing this – just use a Spring MVC server-side web app for example. So I really wanted to solve the problem running the frontend on a completely different machine.
After some initial frustration that this was troublesome, I explored the possibilities:
- Use JSONP. The essence of this solution is this: the javascript code of the calling HMTL page will emit <script> tags into the html page. Once these script tags appear in the HMTL code, the browser will load the javascript sources and thereby do GET requests against the API you wish to call. The returned data needs to be JSON and wrapped in a JavaScript function. The clear downside is that you are limited to GET requests, further need to massage the returned JSON (wrap in javascript functions) and have limited error handling.
- Use a proxy. Sure, I could have written a server-side component which is hosted on the same machine as the one serving the Javascript placign the API calls. The huge downside is the extra server-side component which seems completely redundant.
- Use CORS. Yep, that’s the cool solution. Cross-Origin Resource Sharing is very simpel and supported by all recent browsers. You simply have to retun a Response Header in the API responses and a browser that supports CORS will then let the AJAX requests pass. The response header is this:
Access-Control-Allow-Origin: *
The big benefit here really is, that I can use plain AJAX calls including all HTTP verbs (POST, PUT, DELETE, etc.) not just GET. It feels like you are using the RESTful API from a native mobile client, where you also do not have to worry about the same origin policy.
I’ve put up a tiny demo page that shows how you can quickly search a hybris eCommerce platform via the OCC Web Services here. This link will expire at some time, but the key takeaway is that there is no special client-side code required. Just plain AJAX. You only need to have control over the API and set the HTTP response header described above.
Let me know what you think of this and if you know of other solutions I am not aware of!
Comments are closed.