【问题标题】:Why does CORS not seem to work with POST?为什么 CORS 似乎不适用于 POST?
【发布时间】:2011-02-03 12:28:41
【问题描述】:

Mozilla 自己的specification 说简单的GETPOST 应该是原生的CORS,没有预检,但到目前为止,我所做的每一次POST 尝试都导致OPTIONS 标头消失。当我将其从 POST 更改为获取代码时,立即发送正确的 GET 请求,因此跨站点部分工作正常。

这是我在 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*/);
            }

这是我已经在 chrome 和 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);

【问题讨论】:

    标签: xmlhttprequest w3c cors


    【解决方案1】:

    好吧,我不知道所有 contentTypes 的实际工作原理,但 text/plain 在所有 3 个浏览器上的作用:

    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);
    

    但是到目前为止,我还没有弄清楚是什么阻止了请求执行除了运行成功方法之外的任何操作,即使返回 505 代码也是如此。添加Access-Control-Allow-Origin: *的响应头解决了浏览器不想读取返回数据的问题。

    【讨论】:

      【解决方案2】:

      我也有同样的问题

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

      说 enctype 必须是 text/plain 或者你需要使用 Fx4+ 所有访问标头都必须正确设置

      【讨论】:

        猜你喜欢
        • 2010-12-23
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 2018-09-28
        • 1970-01-01
        • 2023-02-10
        • 1970-01-01
        相关资源
        最近更新 更多