本地主机和 put 方法的 CORS 问题

CORS issue with localhost and put method

我正在尝试发出 CORS 请求以在位于两个不同域中的客户端和服务器之间进行通信。

服务器 headers 已设置为以下 -

Access-Control-Allow-Headers:Content-Type, Authorization, Content-Length, X-Requested-With Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS Access-Control-Allow-Origin:*

如果我点击服务器,我可以看到响应 header url (http://server.com)

现在,当我使用 jquery 将数据和方法发送到服务器进行处理并取回数据时,我得到以下内容

Failed to load http://server.com/event/live: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3016' is therefore not allowed access. The response had HTTP status code 502.

Jquery代码为--

callMyAPI : function(pUrl,pType,pData,callback){
        var apiURL = API_HOST+pUrl;
        jQuery.ajax({
            xhr: function() {
                var xhr = jQuery.ajaxSettings.xhr();
                xhr.upload.onprogress = function(e) {
                    if (typeof callback == "function"){
                        var percentComplete = parseInt((e.loaded / e.total)*100);
                        callback('progress',percentComplete);
                    }   
                };
                xhr.addEventListener("progress", function(e){
                    if (typeof callback == "function"){
                        if (e.lengthComputable) {
                            var percentComplete = parseInt((e.loaded / e.total)*100);
                            callback('progress',percentComplete);
                        }
                    }   
                }, false);
                return xhr;
            },
            url: apiURL,
            data: pData,
            type: pType,
            beforeSend: function(xhr){
               xhr.withCredentials = true;
            },
            crossDomain: true,
            contentType: 'application/json',
            dataType: 'json',
            success: function(data) {
                if (typeof callback == "function"){
                    callback('success',data);
                }   
            },
            complete: function(){
                if (typeof callback == "function"){
                    callback('complete');
                }
            }
        }).fail(function(xhr, status, error) {
            if (typeof callback == "function"){
                callback('fail',error);
            }   
        });
    },

非常感谢任何帮助。提前致谢。

这与您的 jquery 代码无关。阻止调用的是浏览器。 我建议你确保关注,

  1. 相同的 header 将在上述 http://server.com/event/live 路线上行驶。
  2. 尝试将数据类型作为 xhr 中的 jsonp,如果这解决了问题,那么可以肯定 header 响应不正确(拼写错误或缺少某些内容)。对于您正在执行的项目类型,根本不建议使用 jsonp。
  3. 最重要的是,如果您在该路线上进行 POST/PUT,请确保您回复 OPTIONS 类型的电话(探索 pre-flight 电话)