如何在angular中使用body程序调用POST API [raise 422 error (Unprocessabl



我正在努力使用FastAPI, Angular使用Post API而使用HttpClient。发布函数

在后端FastAPI中接收程序而没有看到程序的问题并抛出422 (Unprocessable Entity)

  • Mybackend API CODE (FastAPI-Python):

from typing import Optional
from pydantic import BaseModel
class UsersLoginRequest(BaseModel):
username: str
password: str

@users_router.post("/login")
def login(body: UsersLoginRequest):
pass
  • 开始后端:
Uvicorn running on http: //127.0.0.1:3101 (Press CTRL+C to quit)
Started reloader process [36366] using WatchFiles
Started server process 363701
Waiting for application startup.
Application startup complete
  • 使用Postman cURL调用API示例:
curl --location --request POST 'http://127.0.0.1:3101/users/login' 
--header 'Content-Type: application/json' 
--header 'Accept: application/json' 
--data-raw '{
"username": "admin",
"password": "admin"
}'

# See trafic ... 
127.0.0.1:54336 - "POST /users/login HTTP/1.1" 200 OK

通过调用this.http.post:

尝试使用angular前端的相同API

import { HttpClient  ,HttpHeaders, HttpParams} from '@angular/common/http';
constructor( private http:HttpClient )
signIn(): void
{ 
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

let params = new HttpParams()
.append('username', "admin")
.append('password', "admin")

debugger
this.http.post('http://127.0.0.1:3101/users/login',params   ,{ headers: headers }
).subscribe({ 
error: (respose:any) => { 
debugger
},    // errorHandler 
next: (respose:any) => {  
debugger
},     // nextHandler 
})

}

后台流量:

INFO:     127.0.0.1:62969 - "POST /users/login HTTP/1.1" 422 Unprocessable Entity

尝试更改参数位置


import { HttpClient  ,HttpHeaders, HttpParams} from '@angular/common/http';
constructor(
private http:HttpClient
)
signIn(): void
{
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');

let params = new HttpParams()
.append('username', "admin")
.append('password', "admin")

debugger
this.http.post('http://127.0.0.1:3101/users/login',null   ,{ headers: headers, params: params }
).subscribe({ 
error: (respose:any) => { 
debugger
},    // errorHandler 
next: (respose:any) => {  
debugger
},     // nextHandler 
})

}

后台流量:

INFO:     127.0.0.1:62969 - "POST /users/login HTTP/1.1" 422 Unprocessable Entity

我不知道我错过了什么!!!!* *我试图在python中接收body程序- FastAPI

记录::

我试过这个位置,它不工作

Angular中HTTPparams 422 (Unprocessable Entity)和FastAPI出错

你可以看到上面的例子…

尝试发送对象而不是http参数。例如:

this.http.post('http://127.0.0.1:3101/users/login',{user: "foo", password: "bar"},{ headers: headers })

它可能是你正在发送一个http表单?

相关内容

  • 没有找到相关文章

最新更新