簡體   English   中英

本地主機和放置方法的 CORS 問題

[英]CORS issue with localhost and put method

我正在嘗試發出 CORS 請求,以便在位於兩個不同域中的客戶端和服務器之間進行通信。

服務器標頭已設置為以下內容 -

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:*

如果我點擊服務器 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. 如上所述,相同的標頭出現在http://server.com/event/live路由上。
  2. 在 xhr 中嘗試將數據類型設為 jsonp,如果這解決了問題,在這種情況下,可以肯定標頭響應不正確(拼寫錯誤或缺少某些內容)。 對於您正在執行的項目類型,根本不建議使用 jsonp。
  3. 最重要的是,如果您在該路由上執行 POST/PUT,請確保您回復 OPTIONS 類型的呼叫(探索飛行前呼叫)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM