以下是我的代码
@app.route('/<string:article_id>/<int:n>', methods=['GET'])
def get_similar(article_id,n):
df = pd.read_csv('data.csv',usecols=['article','similar'])
df['article']=df.article.str.replace('.txt ?','')
df['similar']=df.similar.str.replace('.txt ?','')
if n<df.article.nunique():
if any(df.article==article_id):
df5=df[df['article'].isin([article_id])]
df5=df5.similar
df5=df5[0:int(n)]
df5.index=range(int(n))
x=df5.to_json(orient='columns')
data = {}
data['success'] = 'true'
y= json.dumps(data)
res = json.loads(y)
res['data'] = json.loads(x)
res_str = json.dumps(res, sort_keys=True)
return (res_str)
else:
data = {}
data['success'] = 'false'
json_data = json.dumps(data)
return json_data
else:
data = {}
data['success'] = 'false'
json_data = json.dumps(data)
return json_data
我收到以下错误
XMLHttpRequest cannot load http://107.20.3.77:8286/919/5. Response to
preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:8001' is therefore not allowed access.
有人可以帮我避免这个错误。当我尝试卷曲它的工作但在前端它没有工作。
答案 0 :(得分:0)
你可以使用这个装饰。
from flask import current_app, make_response, request
from functools import wraps, update_wrapper
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
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)
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
然后你可以声明这样的路线
@app.route('/api/v1/user', methods=['OPTIONS', 'POST'])
@crossdomain(origin="*")
def add_user():
pass