如何解决使用 axios 指定标题的正确方法是什么?
我在测试我的应用时正在处理跨源头:
反应面:
const url = "http://localhost:5000/blog/posts";
const headers = { headers: "Access-Control-Allow-Origin" };
axios.post(url,data,headers).then( ...
Flask 后端 __init__.py
:
...
...
from flask_cors import CORS
def create_app(script_info=None):
app = Flask(__name__)
from project.api.blog import blog_blueprint
from project.api.auth import auth_blueprint
CORS(blog_blueprint,resources={'origin': ['http://localhost:3000']})
app.register_blueprint(blog_blueprint)
app.register_blueprint(auth_blueprint)
return app
上面在 try-catch
语句的 catch 块中给了我一个异常:
TypeError: name.toupperCase is not a function
使用 Flask 的默认值,这意味着将端点暴露给任何域:
from project.api.blog import blog_blueprint
from project.api.auth import auth_blueprint
CORS(blog_blueprint)
给我Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/blog/posts. (Reason: CORS header 'Access-Control-Allow-Origin' missing)
我也尝试使用 Flask-CORS 的装饰器:
from flask_cors import cross_origin
class BlogPosts(Resource):
@cross_origin()
def post(self):
parser.add_argument('category',type=str)
parser.add_argument('title',type=str)
parser.add_argument('post',type=str)
args = parser.parse_args()
new_post = Posts(title=args.title,category=args.category,post=args.post)
db.session.add(new_post)
db.session.commit()
return {'status': 'success','message': 'post added'},201
非常感谢任何帮助。
解决方法
奇怪的是,我通过将代码重构为基于函数的视图来解决我的问题:
CORS(blog_blueprint)
@blog_blueprint.route('/posts',methods=['GET','POST'])
@cross_origin()
def blog_posts():
if request.method == 'POST':
post_data = request.get_json()
category = post_data.get('category')
title = post_data.get('title')
post = post_data.get('post')
new_post = Posts(title=title,category=category,post=post)
db.session.add(new_post)
db.session.commit()
return {'status': 'success','message': 'post added'},201
return {'status': 'success','message': [post.to_json() for post in Posts.query.filter_by(category=category)]},200
我对此不太满意,因为无论我使用基于类还是基于函数的视图来处理 API,Flask 的 CORS 库都应该以相同的方式工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。