我需要通过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。
发布于 2014-03-05 04:32:22
通过使用这个decorator,并将“选项”添加到我的可接受方法列表中,我获得了使用Flask的Javascript。装饰器应该在你的路由装饰器下面使用,如下所示:
@app.route('/login', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def login()
...
编辑:链接似乎已断开。这是我用过的装饰器。
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None, max_age=21600,
attach_to_all=True, automatic_options=True):
"""Decorator function that allows crossdomain requests.
Courtesy of
https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html
"""
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
# use str instead of basestring if using Python 3.x
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
# use str instead of basestring if using Python 3.x
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
""" Determines which methods are allowed
"""
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
"""The decorator function
"""
def wrapped_function(*args, **kwargs):
"""Caries out the actual cross domain code
"""
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
h['Access-Control-Allow-Credentials'] = 'true'
h['Access-Control-Allow-Headers'] = \
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
发布于 2015-09-24 04:58:00
我使用过flask-cors扩展。
使用pip install flask-cors
安装
那就很简单了
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
这将允许所有域
发布于 2017-02-17 07:13:11
老问题,但对于有这个问题的未来谷歌用户,我在我的flask-restful应用程序中解决了这个问题(以及其他一些与CORS有关的下游问题),在我的app.py文件中添加了以下内容:
app = Flask(__name__)
api = Api(app)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
if __name__ == '__main__':
app.run()
https://stackoverflow.com/questions/22181384
复制相似问题