由于浏览器受同源策略的限制,在使用 XMLHttpRequest 对象进行跨域请求时,通常会报 No ‘Access-Control-Allow-Origin’ header is present on the requested resource 错误,导致请求失败。
解决该问题的基本思路是使用 CORS(Cross-Origin Resource Sharing)
或 JSONP
,具体到 Flask 场景R,方法如下。
(1)导入flask_cors 模块
pip install flask_cors
(2)配置代码如下
伪代码 :
from flask import Flask
## 1、导入flask_cors 模块 ,pip install flask_cors
from flask_cors import CORS
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
@app.route('/',methods=['GET', 'POST','OPTIONS'])
def hello(resp):
data ={
"status":200,
"message":'查询成功',
"list":[
{
"name":"张三",
},
{
"name": "李四",
},
{
"name": "wangwu",
}
]
}
json_str = json.dumps(data, ensure_ascii=False)
resp = make_response(json_str)
# 2、headers 中进行设置
resp.headers["Content-Type"] = "application/json;chartset=UTF-8" # 设置响应头
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS' # 如果有其它方法(delete,put等),断续添加
resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return resp
if __name__ == '__main__':
app.run(debug=True)
## 3、调用 CORS
CORS(app)
完整代码如下:
import json
from flask import Flask,make_response,request, url_for, redirect, render_template
## 1、导入flask_cors 模块 ,pip install flask_cors
from flask_cors import CORS
app = Flask(__name__) # 在当前文件下创建应用
app.config['JSON_AS_ASCII'] = False
@app.route('/',methods=['GET', 'POST','OPTIONS'])
def hello():
data ={
"status":200,
"message":'查询成功',
"list":[
{
"name":"张三",
},
{
"name": "李四",
},
{
"name": "wangwu",
}
]
}
json_str = json.dumps(data, ensure_ascii=False)
resp = make_response(json_str)
# 2、headers 中进行设置
resp.headers["Content-Type"] = "application/json;chartset=UTF-8" # 设置响应头
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS' # 如果有其它方法(delete,put等),断续添加
resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return resp
if __name__ == '__main__':
app.run(debug=True)
## 3、调用 CORS
CORS(app)