我需要通过发送数据XmlHttpRequest
从 JavaScript 到 Python 服务器。因为我使用的是本地主机,所以我需要使用CORS。我正在使用 Flask 框架及其模块flask_cors
.
作为 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 无法加载 localhost:5000/signin。不
请求中存在“Access-Control-Allow-Origin”标头
资源。因此,不允许访问来源“null”。
我应该如何修复它?我知道我需要使用一些“Access-Control-Allow-Origin”标头,但我不知道如何在这段代码中实现它。顺便说一句,我需要使用纯 JavaScript。
我已经用过烧瓶-cors扩大。
安装使用pip install flask-cors
那么就简单了
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
这将允许所有域
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)