【问题标题】:Sanic CORS Exception handlerSanic CORS 异常处理程序
【发布时间】:2020-09-13 15:32:20
【问题描述】:

我尝试在异常处理程序中使用 Sanic_CORS,例如错误 404, 但我收到 CORS 错误 Access to XMLHttpRequest at 'http://backend:port/endpoint' from origin 'http://react_app:port' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 有效端点没有问题。

我的错误处理程序

@app.exception(NotFound)
async def ignore_404s(request, exception):
    return response.json({'message': "Oops, server error"},
                          status=404)

如何为错误处理程序实现 Sanic_CORS?有任何想法吗?

【问题讨论】:

    标签: sanic flask-cors


    【解决方案1】:

    一种选择是将标题添加到您的响应中。虽然,这不是使用sanic-cors 包,但你在这里真的不需要它。

    @app.exception(NotFound)
    async def ignore_404s(request, exception):
        return response.json(
            {'message': "Oops, server error"},
            status=404,
            headers={"Access-Control-Allow-Origin": "*"}
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 2019-05-25
      • 2020-05-17
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多