Flask 如何正确设置带有CORS和授权标题的烧瓶
我想在我的flask应用程序中设置CORS,添加flask CORS在一定程度上会有所帮助。虽然“CORS(应用)”对所有不需要授权的路由都有帮助,但我无法访问需要授权的路由 有一条路线是这样的Flask 如何正确设置带有CORS和授权标题的烧瓶,flask,fetch,http-status-code-502,Flask,Fetch,Http Status Code 502,我想在我的flask应用程序中设置CORS,添加flask CORS在一定程度上会有所帮助。虽然“CORS(应用)”对所有不需要授权的路由都有帮助,但我无法访问需要授权的路由 有一条路线是这样的 @users_blueprint.route('/users/<user_id>', methods=['GET']) @authenticate def get_single_user(resp, user_id): response_object = { 'status': 'f
@users_blueprint.route('/users/<user_id>', methods=['GET'])
@authenticate
def get_single_user(resp, user_id):
response_object = {
'status': 'failure',
'message': 'Invalid Payload'
}
if resp != user_id:
response_object['message'] = 'You are not authorized to view this user'
return jsonify(response_object), 400
try:
user = User.query.filter_by(user_id=user_id).first()
if user:
response_object['status'] = 'success'
response_object['data'] = user.to_json()
return jsonify(response_object), 200
else:
response_object['message'] = 'The user does not exist'
return jsonify(response_object), 400
except (exc.IntegrityError, ValueError, TypeError) as e:
db.session().rollback()
return jsonify(response_object), 400
但是,当我试图通过fetch从React应用程序中访问有问题的路由时,我会出现以下错误:
加载失败
我的路线:没有
“Access Control Allow Origin”标头出现在请求的服务器上
资源。因此,不允许使用源“”
通道响应的HTTP状态代码为502。如果一个不透明的响应
根据您的需要,将请求的模式设置为“无cors”以获取
已禁用CORS的资源
我还能做什么
编辑
当我通过CURL发送一个选项请求时,我可以看到我的路由将以“access control allow”头响应。所以我真的不知道发生了什么。这也是我的取回请求:
const url = `myurlendpoint/myuserid`
const token = my_id_token
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
fetch(url, options)
.then(response => console.log(response.json()))
.catch(error => console.log(error))
另外:当我在没有标题“授权”的情况下调用我的路由时,我得到的正确响应是“未提供授权”,而不是交叉源问题。如果这条路线真的没有跨原点允许设置,那么它应该在我的请求中声明未经授权,对吗?所以它与授权标题有关…您是否尝试过CORS(app,expose\u headers='Authorization')
?此外,如果您解决了问题,请自行回答问题并提供文档
const url = `myurlendpoint/myuserid`
const token = my_id_token
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
fetch(url, options)
.then(response => console.log(response.json()))
.catch(error => console.log(error))