I keep getting the 422 Unprocessable Entity
with those missing fields:
{"detail":[{"type":"missing","loc":["body","username"],"msg":"Field required","input":null},{"type":"missing","loc":["body","password"],"msg":"Field required","input":null}]}
I tried everything possible but the error persists
This is my frontend code:
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const handleLogin = async (e) => {
e.preventDefault();
const formData = new URLSearchParams();
formData.append('username', email); // Assuming the backend expects 'username'
formData.append('password', password);
try {
const response = await fetch('http://localhost:8000/token', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Login failed');
}
and this is on the backend:
@fastapi_router.post("/token", response_model=Token)
async def login_for_access_token(
username: Annotated[str, Form()],
password: Annotated[str, Form()],
db: AsyncSession = Depends(database.get_db)
):
user = await auth.authenticate_user(db, username, password)
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=envs.access_token_expire_minutes)
access_token = auth.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
logger.info(f"Access Token: {access_token}")
return {"access_token": access_token, "token_type": "bearer"}
Any help would be appreciated.