async function test() {
const url = 'работающая api';
var mydata = { username: 'test123', password: 'test123' };
var data = new FormData();
data.append("json", JSON.stringify(mydata)); try { const response = await fetch(url, {
method: 'POST',
body: data,
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log('Успех:', JSON.stringify(json));
} catch (error) {
console.error('Ошибка:', error);
}
}
test().then((data)=>console.log(data))
message error 422:
{"detail":[{"loc":["body","username"],"msg":"field required","type":"value_error.missing"},{"loc":["body","password"],"msg":"field required","type":"value_error.missing"}]}
Серверный код
from fastapi.param_functions import Depends
from fastapi.security import OAuth2PasswordRequestForm
@registr_router.post("/login")
async def login(request: OAuth2PasswordRequestForm = Depends()) -> dict:
user = await registr.check_auth(request.username)
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='User doesnt exist')
if not verify_password(request.password, user['password']):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": request.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
oauth.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from app.auth.JWTtoken import verify_token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='login')
async def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
credentails_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return verify_token(token, credentails_exception)
'Content-Type': 'application/json'
или все-такиvar data = new FormData();