我需要通過XmlHttpRequest從JavaScript發送數據到Python服務器。因爲我使用本地主機,所以我需要使用CORS。我正在使用Flask框架和他的模塊flask_cors。如JavaScript我有這樣的:Javascript - 沒有「訪問控制允許來源」標題出現在請求的資源
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "http://localhost:5000/signin", true);
var params = "email=" + email + "&password=" + password;
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(params);
和Python代碼:
@app.route('/signin', methods=['POST'])
@cross_origin()
def sign_in():
email = cgi.escape(request.values["email"])
password = cgi.escape(request.values["password"])
但是當我執行它,我會得到這個消息:
XMLHttpRequest cannot load localhost:5000/signin. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
我應該怎樣解決這個問題?我知道我需要使用一些「Access-Control-Allow-Origin」標題,但我不知道如何在此代碼中實現它。順便說一下,我需要使用純JavaScript。謝謝
「NameError:name'crossdomain'is not defined」。我應該導入什麼來修復它? –
您需要將鏈接中的裝飾器複製並粘貼到Flask應用程序中。一旦在那裏,crossdomain將被定義,一切都將工作。 –
Python 3.x用戶的重要注意事項:在帖子中鏈接到的裝飾器代碼對Python 3.x不起作用。它給出「NameError:name」basestring'未定義「錯誤,因爲basestring在Python 3.x中不可用。如果你通過使用「list」而不是「basestring」來改變代碼,它就可以工作。 – Zafer