簡體   English   中英

Angular/FastAPI 422 不可處理的實體錯誤

[英]Angular/FastAPI 422 Unprocessable Entity error

我遇到問題並從我的 FastAPI 服務器收到 422 響應錯誤。 我知道它收到的請求與它期望的 pydantic 模型不匹配,但我不知道為什么。

這是我的請求模型:

@authenticate.post("/token", response_model=Token)
async def login_for_access_token(
        form_data: OAuth2PasswordRequestForm = Depends()):
    print(form_data)
    user = authenticate_user(
        form_data.username,
        form_data.password
    )
    print(f'User @ 104 = {user}')
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=login_utility.get_expiration_time())
    access_token = create_access_token(
        data={"sub": user['username']}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}

我使用以下方式從 Angular 應用程序發送請求:

我的有效載荷:

{"username": blah, "password":password}
postTypeRequest(url: string, payload: any) {
    console.log(payload)
    console.log(this.REST_API_SERVER+url)
    return this.httpClient.post(
      this.REST_API_SERVER+url, payload).pipe(map(res => {
      return res;
    }));
  }

我在通過 Postman 發送請求時沒有遇到任何問題。 我是使用 JavaScript/Angular 的新手,我不確定自己做錯了什么。

根據文檔

OAuth2 指定當使用“密碼流”(我們正在使用)時,客戶端/用戶必須發送usernamepassword字段作為form數據。

... usernamepassword必須作為form數據發送(因此,這里沒有JSON )。

.... OAuth2PasswordRequestForm是一個類依賴項,它聲明一個form主體:

  • username
  • password
  • ...

因此,您應該將憑據作為form數據發送。 看看這里這里這里如何做到這一點。

負載不應該是:{username: "blah", password: "password"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM