我在前端使用 axios 处理请求,并使用 FastAPI 作为 Python 后端。我正在尝试添加授权标头,但不知何故它不起作用。设置标头时,它永远不会出现,甚至在 axios 请求本身中也不会出现:
我这样构建我的请求:
async get_species_list() {
if (this.species_list !== null) return this.species_list;
const userStore = useUserStore();
const config = {
headers: {
Authorization: `Bearer ${userStore.token}`,
},
};
try {
const response = await axios.get(
`${API_BASE_URL}${SPECIES_DICT_ENDPOINT}`,
config
);
console.log(response.data.headers); // this yields 'undefined'
const speciesAndBreeds = response.data;
} catch (error) {
console.error("Error fetching species and breeds:", error);
}
},
在我的后端我有:
...
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost",
"http://localhost:8080",
"http://localhost:3000",
"http://127.0.0.1",
"http://127.0.0.1:8080",
"http://127.0.0.1:3000",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
...
@app.get("/species-breeds")
async def get_species_list(header=Header(default=None)):
print(header) # which just print 'None'
)
你可以发布代码
const userStore = useUserStore();