javascriptjqueryweb-servicescorssap-business-technology-platform

jQuery POST to webservice via CORS


I have read a lot of topics about CORS & Javascript and about changing the headers in your post but I can't find the right example I am looking for.

So I'm going to first up start with explaining the situation:

The problem I have is described in the following Post: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

--> My FF & Chrome Headers send a METHOD OPTIONS instead of METHOD POST.

I have written example code that works in IE but not in FF & Chrome:

var dataString = "<result><firstname>example</firstname><lastname>ThisIsSparta</lastname></result>";
    var urlString = "http://delyo001.you.local:8000/sap/bc/youconsulting/ws/rest/anonymous/z_names_post";

    //Add TO SAP.
    var aData =  
            jQuery.ajax({
                type: "POST",
                contentType: "application/xml",
                url: urlString,  // for different servers cross-domain restrictions need to be handled
                data: dataString,
                dataType: "text",
                success: function(xml) { // callback called when data is received
                    //oModel.setData(data);             // fill the received data into the JSONModel
                    alert("success to post");
                },

                error: function(xml) { // callback called when data is received
                    //oModel.setData(data);             // fill the received data into the JSONModel
                    alert("fail to  post");
                }
            });
        });

Or

var invocation = new XMLHttpRequest();
var url = 'http://delyo001.you.local:8000/sap/bc/youconsulting/ws/rest/anonymous/z_names_post';
var body = '<result><firstname>perthyrtyrtygop</firstname><lastname>sparta</lastname></result>';


   invocation.open('POST', url, true);
   invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
   invocation.setRequestHeader('Content-Type', 'application/xml');
   invocation.send(body);

I have found 2 ways to fix this but without any examples: - do something with a proxy? - send specific headers

More information about my problem can be found at: - http://scn.sap.com/message/13697625#13697625


Solution

  • If you can't set the right headers on the server-side and you can't modify the response for jsonP you should indeed use a proxy.

    A proxy script is a sort of middleware. You make a request to the script the script gets the data, and returns it to you. For example php proxy. You can make the same thing in asp, jsp, flash or even java applet.

    Now you have your SAP service, a proxy (php)file in a your prefered location, and your local javascript in the same domain as the proxy. You don't even need CORS.

    If you want to put the proxy in another domain you have to make sure the php file sends the right headers. (Access-Control-Allow-Origin yourdomain or Access-Control-Allow-Origin * for allow all)