PDA

View Full Version : Cross Origin Resource Sharing



Sameer Khan
11 Jan 2012, 11:26 PM
Hi, I want to do cors with my sencha touch application...Bcz here i am posting huge amount of data to .net server..so JSONP supports only get method..
so here i converted my Oject data to xml stirng format and sending the xml string to .net server with XmlHttpRequest() object by writing some header for xmlhttpreq obj to make communcaion with .net server...

But here the problem is .NET server webservice call always ruturns status code-0.

Plz any one help me...Its Urgent...Thanks..

following is the code:
----------------------

At cleint side:
--------------
var body="Hi! How is CORS?";
xmlhttp.open('POST', 'http://192.168.1.1/zephyr/SERVICE-HANDLERS/ClientList.ashx',true);

//Headers to xmlhttprequest object
xmlhttp.setRequestHeader('Access-Control-Request-Method', 'POST');
xmlhttp.setRequestHeader('Origin', 'http://192.168.1.1/zephyr'); // Doubt here on Domain Name
xmlhttp.setRequestHeader('Content-type', 'text/plain');
xmlhttp.setRequestHeader('X-PINGOTHER', 'pingpong')
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.withCredentials = "true";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200){
document.getElementById('result').innerHTML = "Result is:"+xmlhttp.responseText;
document.getElementById('result').innerHTML+="\n"+xmlhttp.getAllResponseHeaders();
}
else if (xmlhttp.status==404)
document.getElementById('result').innerHTML = "Status Code: "+xmlhttp.status;
else
document.getElementById('result').innerHTML = "Status Code: "+xmlhttp.status;

}
}
xmlhttp.send(body);

2. At server side:
-------------------
context.Response.Write(output);
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");// header provided to send response

mitchellsimoens
12 Jan 2012, 7:27 AM
So you need to have your server respond with a different status code correct?

justinKohactive
12 Jan 2012, 5:09 PM
Check out my gist:


https://gist.github.com/1138262


Just use that file as a middleware appliance.

Also your sencha code looks way too complicated. Just use the standard sencha ajax stuff. the browser will do all the heavy lifting for you automatically.

[EDIT]
Ooops i see you using .NET, i am not familair with doing CORS and .NET, i handle the preflight problem at the server level, so that wont work for you. Basically you need every request made to your server to server back certain headers when requested with the OPTIONS method. There is probably a trick to this on .NET i do not know what it is. Also all your CORS enabled controllers need about half of the same headers. Hopefully you can follow the code in the GIST and port it to .NET, if you do end up doing that please open source it as it may help someone else ;)