我尝试在异常处理程序中使用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-cors
包,但您在这里真的不需要它。
@app.exception(NotFound)
async def ignore_404s(request, exception):
return response.json(
{'message': "Oops, server error"},
status=404,
headers={"Access-Control-Allow-Origin": "*"}
)