CORS问题在使用Flask + Typescript进行POST请求时出现。

huangapple go评论57阅读模式
英文:

CORS issue on a POST request using Flask + Typescript

问题

这是我的Python代码的一部分

所有依赖项都已正确导入,但我没有在这里添加代码。

出于某种原因,这段代码(注意末尾的斜杠)

这段代码正常工作,但当我删除末尾的斜杠时,它不起作用,尽管我的代码中定义了这两个路由

我尝试交换这些路由的位置,在我的代码中删除其余路由以防有冲突的路由,在方法中删除所有代码以防某些代码在那里失败,使用CORS配置选项指定标头、方法和路由……我的所有尝试都没有成功。

值得注意的是,当我使用postman时,这个方法是有效的(所以路由似乎被正确定义了)。

解决方案可能就在我眼前,但我没有看到它(值得一提的是,我对Python很陌生)。

任何帮助将不胜感激。

英文:

This is part of my python code

app/products/__init__.py
bp_products = Blueprint('products', __name__, url_prefix='/products')

@bp_products.route('', methods=['POST', 'OPTIONS'], endpoint='add')
@bp_products.route('/', methods=['POST', 'OPTIONS'], endpoint='add')
@json_response
def add():
    if request.json is None:
        abort(400, 'Request must be json')

    # Some logic here

    return product_schema.dump(product)
app/__init__.py
with app.app_context():
        # Some logic here
        CORS(app)

    from .products import bp_products
    app.register_blueprint(bp_products)

All dependencies were properly imported but I didn't add the code here.

For some reason, this code (note the trailing slash)

let response = await fetch(`${apiUrl}/products/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        asin: productAsin,
        process: 1,
      }),
    });

works properly but when I remove the trailing slash, it doesn't work, despite both routes were defined on my code

@bp_products.route('', methods=['POST', 'OPTIONS'], endpoint='add')
@bp_products.route('/', methods=['POST', 'OPTIONS'], endpoint='add')

I tried switching these routes positions, removing the rest of the routes on my code in case there was a conflicting one, removing all the code inside my method in case some code was failing there, specifying headers, methods and routes using CORS config options... none of my attempts were successful.

It's worth noting that this works when I use postman (so the route seems to be properly defined).

The solution may be in front of my eyes but I am not seeing it (it's worth noting I am new to Python).

Any help would be much appreciated.

答案1

得分: 1

这个装饰器 @cross_origin() 起到了作用。
一旦我添加了它,这两个路由都开始正常工作了(有斜杠和没有斜杠的情况都可以)。
我不确定为什么只有对没有斜杠的路由才需要这样做。如果有人知道原因,我渴望了解。

英文:

This decorator @cross_origin() made the trick.
Once I added it, both routes started to work (with and without the trailing slash).
I am not sure why this is only necessary for the route without a trailing slash on it. If someone knows the reason, I am eager to know it.

huangapple
  • 本文由 发表于 2023年6月13日 03:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定