【问题标题】:Not able to get request headers in http interceptors python fastapi while sending request using axios使用axios发送请求时无法在http拦截器python fastapi中获取请求标头
【发布时间】:2022-01-20 23:07:55
【问题描述】:

我正在使用快速 API 服务器并公开了 api。从我的 JS 使用 axios 我正在调用这个服务器。

我正在使用拦截器检查headers 中的token

我也加了CORSMiddleware

这里是代码

origins = ["*", "http://localhost:3002"]

# Creating FastAPI Application
app = FastAPI()


app.include_router(chat_service.router)
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

和拦截器

@app.middleware("http")
async def verifyJWT(request: Request, call_next):
    try:
        token = request.headers['token']
        ...
    except:
        return JSONResponse(content={
            "err": "You are not authorized"
        }, status_code=401)

这是来自 JS 的代码,使用 axios

$.ajax({
    url: url,
    type: "POST",
    crossDomain: true,
    contentType: "application/json",
    headers: {
        "accept": "*/*",
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json" ,
        "token": TOKEN
    },
    data: my_data,
    success: function (botResponse, status) {
        ...
    },
    error: function (xhr, textStatus, errorThrown) {
         .. .
    }
});

我在headers 中传递token

但在 Fast api 服务器上它会抛出错误,因为标头中没有令牌

并在控制台上显示

Access to XMLHttpRequest at 'http://localhost:8082/api/process' from origin 'http://localhost:3002' 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.

如果我从ThunderClient 拨打电话,它可以工作。

可能是什么问题,我该如何解决?

【问题讨论】:

    标签: python axios cors http-headers fastapi


    【解决方案1】:

    问题在于您的origins = ["*", "http://localhost:3002"]。据我了解,当您在中间件中设置allow_credentials=True 时,您不能将通配符(即"*")用于allow_origins。 这是文档的摘录。

    allow_credentials - 表示跨域请求应该支持 cookie。默认为假。此外,allow_origins 不能设置为 ['*'] 以允许凭据,必须指定来源。

    此处的文档链接:https://fastapi.tiangolo.com/tutorial/cors/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2014-04-01
      • 2022-01-15
      • 2020-07-03
      • 1970-01-01
      相关资源
      最近更新 更多