Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MooTools CORS request vs native Javascript

I have this MooTools code:

new Request.JSON({
  method: 'POST',
  url: URL, /*URL TO ANOTHER DOMAIN*/
  onSuccess: function(r){
    callback(r);
  }
}).post(data);

And this code doesn't send POST requests (OPTIONS only)... Look at the code below (it works great):

var http = null,
  params = Object.toQueryString(data);
try {
  http = new XMLHttpRequest();
} catch (e) {
  try {
    http = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      http = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      http = null;
      alert("Your browser does not support AJAX!");
    }
  }
}
var url = URL;
http.onreadystatechange = function () {
  if (http.readyState == 4 && http.status == 200) {
    var jsonData = JSON.parse(http.responseText); /*OR EVAL*/
    callback(jsonData);
  }
};
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(params);

EDIT:

Tried: .setHeader('Content-Type','application/x-www-form-urlencoded');
Still nothing... Where can there be a problem?

Thanks!

like image 831
XTRUST.ORG Avatar asked Feb 16 '23 11:02

XTRUST.ORG


1 Answers

This is because MooTools bundles some extra stuff with the request headers.

eg. if your htaccess says:

Header set Access-Control-Allow-Origin: *

you need to craft your request like that:

var foo = new Request({
    url: 'http://fragged.org/Epitome/example/data/',
    method: 'get',
    onComplete: function (data) {
        // returns an object with name and surname  
        new Element('div[html="{name} {surname}"]'.substitute(JSON.decode(data))).inject(document.body);
    }
});

// need to remove that or CORS will need to match it specifically
delete foo.headers['X-Requested-With'];
foo.send();    

This is why you are only seeing the OPTIONS pre-flight. It does not like you :)

You could change the .htaccess to also match X-Requested-With, which is probably some extra "security".

See http://jsfiddle.net/7zUSu/1/ for a working example - I did that a while ago when I wanted to get this change to Request https://github.com/mootools/mootools-core/issues/2381 fixed.

like image 125
Dimitar Christoff Avatar answered Mar 05 '23 18:03

Dimitar Christoff