This js code below is the code that sends a login request to my fastapi server in React.
const onSubmitHandler = (event) => {
event.preventDefault();
fetch("http://127.0.0.1:8000/api/v1/user/login", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({
username: Username,
password: Password,
}),
}).then((res) => {
console.log(res);
if (res.status === 200) {
setCookie("access_token", res.data.access_token);
setCookie("token_type", res.data.token_type);
setCookie("username", res.data.username);
setCookie("is_login", true);
navigate(`/`);
return;
}
if (res.status === 401) {
alert("Incorrect username or password");
return;
}
alert("Error");
});
};
The Python code below is the code that handles login requests in my Fastapi.
@router.post("/login", response_model=schemas.Token)
def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db)
):
user = crud.get_user_by_username(db, form_data.username)
if not user or not crud.pwd_context.verify(form_data.password, user.password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
data = {
"sub": user.username,
"exp": datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
}
access_token = jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
print(f"access_token: {access_token} (type: {type(access_token)})")
return schemas.Token(
access_token=access_token,
token_type="bearer",
username=user.username
)
<starlette.requests.Request object at 0x000001E784693E50> 2 validation errors for Request body -> username field required (type=value_error.missing) body -> password field required (type=value_error.missing)
My error code is as above.
Maybe my question is stupid
I am getting this 422 error because the data type is different. I know what happens when there is no data. In my case, when I look at the error code, there is no data, but I don't know why there is no data.
I tried changing the header to "content-type": "application/json" and creating an exception_handler to display an error message, but I still don't know why this problem occurs.