2017-04-19 73 views
1

我遇到了一些問題,「跨源請求被阻止」。我試圖首先從服務器,而不是從所有(「*」)。每次在Chrome開發人員工具包上都收到相同的錯誤消息。使用燒瓶和ajax的跨原點問題

這裏是我的燒瓶Python代碼:

application = Flask(__name__) 
application.config.from_object(__name__) 
cors = CORS(application, resorces={r'/*': {"origins": '*'}}) 

@application.route("/get-live-data",methods=['GET']) 
@cross_origin() 
def live_data(): 
    con = connect_db() 
    cur = con.cursor() 
    cur.execute("SELECT * from envoiContinuT") 
    sqlite_result = cur.fetchall() 
    cle = json.load(open(JSON_STATUS)) 
    parametres = json.load(open(JSON_PARAMETRES)) 
    descT = [] 
    for key in cle["status"]: 
     attr = parametres[key] 
     if attr["envoiC"] == 1: 
      descT.append(attr["description"]) 
    response = any_response(flask.jsonify(data=descT)) 
    return response 

這裏是我的Ajax代碼:

var baseURL = "http://localhost:8000"; 

function getLiveData(data){ 
    //Get the parameters descriptions 
    $.ajax({ 
     method: 'GET', 
     url:baseURL + '/get-live-data', 
     headers: { 
      "Accept" : "application/json", 
      "Content-type": "application/json" 
     }, 
     success:function(data){ 
       console.log(data); 
       //populateAccordion(data);  
     }, 

     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      console.log("Status: " + textStatus); 
      console.log("Error: " + errorThrown); 
      } 
    }); 
} 

謝謝您的回答!

回答

0

您在這裏有一個錯字:

cors = CORS(application, resorces={r'/*': {"origins": '*'}}) 
         ^^^^^^^^ 

應該是:

cors = CORS(application, resources={r'/*': {"origins": '*'}}) 

此外,還有在發送Content-type請求頭爲GET要求沒有意義的。 GET請求沒有請求主體,所以不需要指定內容類型。因此,而不是隻是這樣做:

headers: { 
    "Accept" : "application/json", 
}, 

否則,如果你發送一個帶有值application/json一個Content-Type請求頭,並觸發您的瀏覽器做一個CORS preflight OPTIONS request,和你的配置必須允許它:

@application.route("/get-live-data",methods=['GET', 'POST']) 
@cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers 

但是,如果你允許Content-Type請求標頭,那麼你也可以允許POST請求(如上所述),因爲如前所述,只允許GET請求允許它。