flask 设置headers['Access-Control-Allow-Origin']='*'实现跨域访问

需要flask将数据发送到web前端,定义一个路由,访问该路由获取数据。
res= make_response(json.dumps(result)):
通过make_response封装数据及类型转换,返回res即可。
一般纯的api接口需要考虑跨域访问问题,下面是简单的跨域访问装饰器在flask中的实现。

from functools import wraps
from flask import make_response
一:
@app.route('/result', methods=['GET', 'POST'])
def index():
    file_object = open('/home/pyspark_project/pyspark_output_result.json')
    try:
        result_text = file_object.read()
    finally:
        file_object.close()
    #
    rst = make_response(result_text)
    rst.headers['Access-Control-Allow-Origin'] = '*'
    # rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    # allow_headers = "Referer,Accept,Origin,User-Agent"
    # rst.headers['Access-Control-Allow-Headers'] = allow_headers
    return rst, 201
    #return result_text, 201 #, {'Content-Type': 'application/json'}

二:
@app.route('/articles_list/contents/')
def json_contents():
    response = make_response(jsonify(response=get_articles(ARTICLES_NAME)))
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST'
    response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type' 
    return response

启动本地Flask Sever,准备响应 ajax

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页