flask - 如何解决:“起源Access-Control-Allow-Origin 不允许。” -- 使用 flask_cors
问题描述
我已经使用烧瓶 CORS 设置了一个服务器,并让它用于将数据发送到我构建的 React Web 应用程序,但是当我去测试 POST 方法时它停止工作,现在它无法发送和接收。Web 应用程序控制台中的错误日志是:“Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Fetch API cannot load http://127.0.0.1:5000/由于访问控制检查。”
我早些时候遇到了这个问题并添加了 flask_cors 并且它工作了一段时间。这是我的服务器代码:
from flask_cors import CORS, cross_origin
app = FlaskAPI(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/": {"origins": "http://localhost:port"}})
# Also fails with this variation
# cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route("/", methods=['GET', 'POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
# Also fails with these variations
# @cross_origin(origin='http://127.0.0.1:5000/',headers=['Content- Type','Authorization'])
# @cross_origin(origin='http://localhost:3000',headers=['Content- Type','Authorization'])
def job_api():
with app.app_context():
job_data = get_job_data()
json_data = jsonify(eqtls=[job.data for job in job_data])
return json_data
if __name__ == "__main__":
app.run(debug=True)
这是我的客户代码:
componentDidMount() {
fetch('http://127.0.0.1:5000/')
.then(res => res.json())
.then((data) => {
this.setState({ job_data: data.eqtls })
})
.catch(console.log)
}
解决方案
您需要在 API 上启用 CORS 策略,以便它可以接受来自不同主机的请求。
只需做一个 google Flask cors,并确保您接受 '*' 或特别是您的 URL。
如果您接受 cors,尽管您应该能够接受所有 CORS,然后使您的 API 足够健壮,这样就不会请求任何讨厌的数据
尝试:
from flask_cors import CORS, cross_origin
app = FlaskAPI(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['CORS_HEADERS'] = 'Content-Type'
@app.route("/", methods=['GET', 'POST'])
@cross_origin()
def job_api():
with app.app_context():
job_data = get_job_data()
json_data = jsonify(eqtls=[job.data for job in job_data])
return json_data
if __name__ == "__main__":
app.run(debug=True)
我阅读了文档,并且可以将 @cross_origin() 添加为简单的装饰器:https ://flask-cors.readthedocs.io/en/latest/#route-specific-cors-via-decorator
推荐阅读
- javascript - React Spring - 平滑滚动屏幕
- php - 尝试将离线数据库与heroku的ClearDB连接时,如何处理“mysqli::real_connect(): (HY000/2006): MySQL server has gone away”错误?
- c - C 库是如何安装的?
- powerbi - PowerBI:基于票数的歌曲排名
- java - ActionListener 中的图标设置
- swift - 订阅了测试 PassthroughSubject
- python - 如何使用 HTML 按钮关闭应用程序
- ios - CloudKit 排除受限实体
- sql - 如何检查字节是否为空 vb.net
- node.js - Firebase 功能:如何维护“应用程序全局”API 客户端?