繁体   English   中英

在使用 axios 发送请求时,无法在 http 拦截器 python fastapi 中获取请求标头

[英]Not able to get request headers in http interceptors python fastapi while sending request using axios

我正在使用快速 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)

这是使用axios的 JS 代码

$.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拨打电话,它就可以工作。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM