[英]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
不能设置为 ['*'],必须指定来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.