I developing a site using Vue and FastAPI. I am currently stuck with the error:
422 Unprocessable Entity
received from a FastAPI Sever. As I understand 422 error cause when the request reached server but the request is in invalid format of data, right?
The route I am sending a request looks like this:
@router.post('/token',response_model=Token)
async def login_for_access_token(form_data : Annotated[OAuth2PasswordRequestForm, Depends()], db : db_dependency):
user = authenticate_user(form_data.username, form_data.password, db)
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate user")
token = create_access_token(user.username, user.id, timedelta(minutes=20))
return {'acess_token' : token, 'token_type': "bearer"}
I understand that the request format for OAuth2PasswordRequestForm should be in the format of FormData() sending from a frontend right?
This is what I did in the frontend
login(username, password) {
// Function to make a login request
username = this.InputUsername
password = this.InputPassword
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
console.log(formData)
axios.post('http://localhost:5001/auth/token', {
formData,
})
.then((response) => {
const { access_token } = response.data;
this.setAuthToken(access_token);
alert("Login")
})
.catch((error) => {
console.error(error);
});
},
I put both username and password in FormData() and send a request to server but still get 422 Error from the server. I have this route I'm facing an error on FastAPI api dashboard and it works perfectly fine this only happen when I tried to send a request from the frontend (Vue)
Can anyone guide me on what I did? Am I wrong here? or Did I misunderstand the request format of OAuth2PasswordRequestForm? Thank you