问题描述
我需要从JavaScript发送数据throught XmlHtt prequest到Python服务器。因为我使用本地主机我需要使用CORS。我使用的瓶框架和他模块flask_cors。如JavaScript我有这样的:
I need to send data throught XmlHttpRequest from javascript to python server. Because I'm using localhost I need to use CORS. I'm using Flask framework and his module flask_cors. As javascript I have this:
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);
和蟒蛇code:
@app.route('/signin', methods=['POST'])
@cross_origin()
def sign_in():
email = cgi.escape(request.values["email"])
password = cgi.escape(request.values["password"])
但是当我执行它我会得到这个消息:
but when I execute it I will get this message:
XMLHtt prequest无法加载本地主机:5000 /登入资讯。没有 访问控制 - 允许 - 原产地标头是present的请求 资源。原产地'空',因此没有允许访问。
我应该如何解决?我知道我需要使用一些访问控制 - 允许 - 起源头,但我不知道如何在此code实现它。顺便说一句,我需要使用纯JavaScript。谢谢
How I should fix it? I know that I need to use some "Access-Control-Allow-Origin" header but I don't know how to implement it in this code. By the way I need use pure javascript. Thank you
推荐答案
我的Javascript瓶用这个的,并添加选项我可以接受的方法列表。该装饰应采用路线的装饰之下,就像这样:
I got Javascript working with Flask by using this decorator, and adding "OPTIONS" to my list of acceptable methods. The decorator should be used beneath your route decorator, like this:
@app.route('/login', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def login()
...
这篇关于使用Javascript - 没有“访问控制 - 允许 - 原产地”标头的请求的资源present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!