prettify

baseline

CORS Cross Origin Resource Sharing Javascript

For many years we were stuck with JSONP if we needed to make a cross domain query.
JSONP was OK except for one major point: The amount of data to send where limited by max URL length and then again it had to be URI encoded.
Now we have a solution supported by all browsers except IE7 & Opera (for some reason). Usage:
var oX;
window.onload = function () {
    oX =new ins.CORS("http://127.0.0.1:45632/aj.ashx", XResult);
    document.getElementById("btnSend").onclick = Send;
};
function XResult(oResult, bError) {
    if (bError) {
        alert("Error: " + oResult);
        return;
    }
    alert(oResult);
};
function Send() {
    oX.send("Numbers\nSum\n23\n45");
}
Library:
if (typeof ins!=="object") ins={};
ins.CORS=function(sUrl, fCB) {
    var that = this;
    this.oX = new XMLHttpRequest();
    this.fCB = fCB;
    this.sUrl=sUrl;
    this.bCors = false;
    this.bJson = (typeof JSON !== "undefined");
    this.nTimeout = 1000;
    this.oTim = null;
    if (typeof this.oX.withCredentials !== "undefined") {
        this.bCors = true;
    } else if (typeof XDomainRequest !== "undefined") {
        this.oX = new XDomainRequest();
        //this.oX.open("POST", sUrl);
    } else {
        this.oX = null;
        throw new Error("Browser not supported. Use:\n"+
        "Chrome 11+\n"+
        "Firefox 4+\n"+
        "Internet Explorer 8+");
    }
};
ins.CORS.prototype.send = function (sData) {
    var that = this;
    this.oX.open("POST", this.sUrl, true);
    if (this.bCors) {
    }
    this.oX.onload = function () {
        clearTimeout(that.oTim);
        that.fCB(this.bJson ?
            JSON.parse(that.oX.responseText) :
            eval("(" + that.oX.responseText + ")")
        );
    };
    if (this.bCors) {
        this.oX.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
        this.oX.setRequestHeader("Content-Length", sData.length);
        this.oX.setRequestHeader("Connection", "close");
    }
    this.oX.send(sData);
    that.oTim = setTimeout(function () {
        that.oX.abort();
        that.fCB("Server did not respond",true);
    }, that.nTimeout);
};
Server (asp.net Generic Handler):
public class aj: IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        Stream stIn = context.Request.InputStream;
        int nLen = (int)stIn.Length;
        byte[] aIn = new byte[nLen];
        stIn.Read(aIn, 0, nLen);
        System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
        string sData = enc.GetString(aIn);

        string[] aData = sData.Split();
        int nA = Convert.ToInt32(aData[2]);
        int nB = Convert.ToInt32(aData[3]);
        int nResult = nA + nB;
        context.Response.AddHeader("Access-Control-Allow-Methods", "POST");
        context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
        context.Response.AddHeader("Access-Control-Allow-Origin", "*");
        context.Response.AddHeader("Access-Control-Allow-Headers", "");
        context.Response.Expires = -1;
        context.Response.CacheControl = "no-cache";    
        context.Response.ContentType = "text/javascript";
        context.Response.Write("[" + nResult.ToString() + "]");
    }
    public bool IsReusable {
        get {return false;}
    }
}

1 comment:

  1. Is there any other way reading post data than using "InputStream" ?

    very nice.

    ReplyDelete