我使用的是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/