如何在AIOHTTP中设置CORS策略

问题描述 投票:0回答:2

我已添加“cors_middleware”,但仍然收到“已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。”错误。

#代码

root_app = web.Application(
    middlewares=[
        cors_middleware(
            allow_all=True,
            origins='*',
            # urls=[re.compile(r"^\/api")],
            allow_credentials=True,
            expose_headers="*",
            allow_headers='*',
            allow_methods=["POST", "PATCH", 'GET','OPTION'],
        ),
    ]
)

#错误

从源“http://localhost:63342”访问“http://localhost:8000/api/v1/user/”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于所请求的资源中。

python-3.x aiohttp
2个回答
4
投票

aiohttp-cors github

 import aiohttp_cors
 from aiohttp import web

 app = web.Application()
 app.router.add_post("/offer", offer)
    
 cors = aiohttp_cors.setup(app, defaults={
   "*": aiohttp_cors.ResourceOptions(
        allow_credentials=True,
        expose_headers="*",
        allow_headers="*"
    )
  })

  for route in list(app.router.routes()):
    cors.add(route)

就我而言,是这样解决的


0
投票

您还可以通过自己为被阻止的请求实现

options
动词来解决此问题。

因此,如果您有这样的请求:

from aiohttp import web

routes = web.RouteTableDef()

....

@routes.post("/email/{session_id}")
async def send_email_request(request: web.Request) -> web.Response:
    session_id = extract_session(request)
    # More code below

您可以像这样实现

options
动词:

@routes.options("/email/{session_id}")
async def send_email_options(_: web.Request) -> web.Response:
    return web.json_response({"message": "Accept all hosts"}, headers=CORS_HEADERS)

其中

CORS_HEADERS
变量定义如下:

CORS_HEADERS = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*"
}

通常,网络浏览器在调用实际的

options
方法之前调用
post
动词。通过此实现,您可以覆盖单个
post
调用
head
调用并避免此错误。

优点是不需要额外的库,而且可以执行非常细粒度的定制。

但是如果您希望所有调用都具有相同的行为,那么您应该使用该库

aiohttp_cors

© www.soinside.com 2019 - 2024. All rights reserved.