Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CORS not seem to work with POST?

Mozilla's own specification says simple GET or POST should be natively CORS's without preflighting but so far every POST attempt I've made has resulted in an OPTIONS header going out. When I change it from POST to get the code immediately sends a proper GET request so the cross site part is working fine.

Here's a slimmed down sample of what I'm doing in firefox:

 var destinationUrl = 'http://imaginarydevelopment.com/postURL';
 var invocation = new XMLHttpRequest();
            if (invocation) {
                invocation.open('POST', destinationUrl, true);
                //tried with and without this line
                //invocation.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                invocation.onreadystatechange = (function Handler() {
                if (invocation.readyState == 4)
                        alert('Request made');
                });
                invocation.send(/* tried with and without data*/);
            }

Here's what I already had working in chrome and IE:

var destinationUrl = 'http://imaginarydevelopment.com/postURL';
var destination = { url: destinationUrl, type: 'POST', success: AjaxSuccess, error: AjaxError,
            dataType: 'text', contentType: 'application/x-www-form-urlencoded'
        };
  destination.data = { 'rows': rowList, 'token': token };
            $jq.ajax(destination);
like image 733
Maslow Avatar asked Apr 01 '10 19:04

Maslow


2 Answers

I have the same problem

https://developer.mozilla.org/En/HTTP_Access_Control

says that the enctype has to be text/plain or you need to use Fx4+ All access headers have to be set correctly

like image 146
mplungjan Avatar answered Sep 28 '22 21:09

mplungjan


well, I don't know what all contentTypes actually work but text/plain does on all 3 browsers:

var destination = { url: destinationUrl, type: 'POST', success: AjaxSuccess, error: AjaxError,
             contentType: 'text/plain'
        };
var postData={ 'anArray': theArray, 'token': token };
            destination.data=JSON.stringify(postData);

$jq.ajax(destination);

However so far I haven't figured out what's stopping the request from doing anything besides running the success method even when a 505 code is returned. Adding a response header of Access-Control-Allow-Origin: * solved the browser not wanting to read the return data.

like image 32
Maslow Avatar answered Sep 28 '22 22:09

Maslow