Search code examples
angularrestfastapihttp-status-code-422http-parameters

Error in Angular with HTTPparams 422 (Unprocessable Entity) and FastAPI


I have this url in backend and need pass c1 like a parameter, c1 is only an example, this method enable or disable an user and give back an "ok"

http://127.0.0.1:8000/admin/enable_disable_account?name=c1

the value is taken from a button

<div *ngFor='let userInfo of users'>
 <ul class="list-group">
    <li class="list-group-item">username -> {{userInfo["username"]}}</li>
    <li class="list-group-item">email -> {{userInfo["email"]}}</li>
    <li class="list-group-item">enable/disable -> {{userInfo["enable"]}}</li>
 </ul>
  <button class="btn btn-primary" (click)="setValor(userInfo['username'])">Enable/Disable</button>   
</div>

The method of the component to managment that click event

    setValor(username): void {
    console.log("click")
    this.adminServ.updateStateUser(username)
    .subscribe(data => {
      
      console.log(data)
    },
    err => {
      console.log("error")
      console.error(err)
    })
  }

And the method in the service

    public updateStateUser(username): Observable<any> {
    let params = new HttpParams()
      .append('name', username)      
    return this.http.post('http://127.0.0.1:8000/admin/enable_disable_account', params)
  }

and i have this error, what is the problem? enter image description here

I copy here the method of the backend, i dont know if it's important to find the problem, it's done with FastAPI

@router.post("/enable_disable_account")
async def enable_disable_account(name: str, current_user: User =   Security(get_current_user, scopes=["admin"])):           
  result = await admin_db.enable_disable_account(name)
  if result:
    return JSONResponse(status_code=status.HTTP_200_OK,
                        content='ok')

Solution

  • this.http.post('http://127.0.0.1:8000/admin/enable_disable_account', params)
    

    this line is incorrect.

    Angular http client post method second parameter is body, and third parameter is options.

    when you want to set query and pass params you need to pass as third parameter. and also you must to send as a object not just HttpParams. Angular Http Client API reference

    this.http.post('http://127.0.0.1:8000/admin/enable_disable_account',null ,{
    params: params
    })