4

我想在我的烧瓶应用程序中设置 CORS 并添加烧瓶cors 帮助到一定程度。虽然“CORS(app)”有助于所有不需要授权的路线,但我无法访问需要授权的路线。

有问题的一条路线如下所示。

@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

我玩弄了CORS设置,到目前为止得到了这个:

#enable CORS
CORS(app, allow_headers=["Content-Type", "Authorization", \
        "Access-Control-Allow-Credentials"], supports_credentials=True)

但是当我尝试通过 fetch 从我的 React 应用程序中访问有问题的路由时,我收到了这个错误:

无法加载 MYROUTE:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:3000 ”。响应的 HTTP 状态代码为 502。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我还能做什么?

编辑

当我通过 CURL 发送一个 OPTIONS 请求时,我可以看到我的路由会以“access-control-allow”-headers 响应。所以我真的不知道发生了什么。这也是我的获取请求:

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))

另外:当我在没有标题“授权”的情况下调用我的路由时,我会得到正确的响应,即“未提供身份验证”,而不是跨域问题。如果这条路线确实没有设置跨域允许,那么它应该在我的请求中声明没有授权,对吧?所以它与 Authorization 标头有关......

4

0 回答 0