使用 Axios HTTP 客户端通过 GET 请求调用 FastAPI 后端时收到 422 错误响应

问题描述 投票:0回答:2

我正在尝试从我的 Vue3 客户端(使用

GET
JavaScript HTTP 客户端)向 FastAPI 服务器发出
axios
请求,并且收到
422
错误响应。据我了解,这种错误消息与错误的输入有关。

这是vue3代码:

import { authToken } from "../main.js"

export default {
  ...
  mounted() {
    const response = axios.get('/checkIsLogged', authToken);
    console.log("authToken" + authToken)
    this.isLoggedIn = response
    console.log("isLoggedin", response)
    if (response) {
      this.title3 = "Mi perfil"
    } else {
      this.title1 = "Sign in"
    }
  },

其中“authToken”

export const authToken = ""

export const setAuthToken = (token) => {
    authToken = token
}

另一方面,在FastAPI中,方法是:

@empresa.get("/checkIsLogged", response_model=bool)
def is_token_expired(authToken: str):
    try:
        payload = jwt.decode(authToken, SECRET_KEY, algorithms=[ALGORITHM])
        expiration_timestamp = payload.get("exp")
        if expiration_timestamp is None:
            return True 
        expiration_datetime = datetime.fromtimestamp(expiration_timestamp)
        current_datetime = datetime.now()
        if current_datetime >= expiration_datetime:
            return True  
        return False 
    except JWTError:
        return False 

我做错了什么?

提前致谢。

javascript python axios vuejs3 fastapi
2个回答
0
投票

您可以在调用 fastpi api 之前打印

console.log("authToken" + authToken
) 吗? authToken 字段中是否有有效值?

下面的方法需要一个有效的字符串,如果输入无效,将抛出 422 错误。

is_token_expired(authToken: str):

还可以通过控制台记录

response.json()
以查看确切的错误。很可能正在生成一些 pydantic 错误

您也可以尝试使用postman调用API


0
投票

axios.get()
方法将请求
config
作为第二个参数,不是直接查询字符串参数。因此,您的
GET
请求应如下所示:

客户端

axios.get('/check', {
  params: {
    authToken: authToken
  }
});

服务器端

@app.get("/check")
def is_token_expired(authToken: str):
    pass

有关

422
错误响应的更多详细信息,请查看 这个答案,它解释了错误并演示了如何在 FastAPI 中发送带有 JSON 数据的
POST
请求。

© www.soinside.com 2019 - 2024. All rights reserved.