使用axios发送请求时,无法在http拦截器中获取请求标头 [英] Not able to get request headers in http interceptors python fastapi while sending request using axios

查看:0
本文介绍了使用axios发送请求时,无法在http拦截器中获取请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Fast API服务器,并公开了API。并且我正在使用axios从我的JS呼叫此服务器。

我正在使用拦截器检查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进行调用,它会起作用。

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

推荐答案

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

allow_credentials-表示跨域请求需要支持cookie。默认为False。此外,allow_origins不能设置为[‘*’]才能允许凭据,必须指定来源。

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

这篇关于使用axios发送请求时,无法在http拦截器中获取请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆