【发布时间】: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