I’m using Fast API to receive form submissions from a React based login page. However, I am receiving a 405 error upon submitting a request from my frontend:
405 Error:
However, when testing out json inputs on the FastAPI endpoint ui, it works fine:
Success:
Below is my frontend page with the form and on submit async funcs:
page.tsx
export default function Goal(){
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
async function onSubmit(event : FormEvent<HTMLFormElement>) {
event.preventDefault()
const formData = {
username: username,
password: password
};
try{
const response = await fetch('http://127.0.0.1:8000/frontend_testing', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData) // Send as JSON
});
// const responseData = await response.json();
}
catch(err){
console.log(err)
}
}
return (
<main>
<div className={inter.className} style={{
color: '#4C4C4C',
fontSize: 24,
fontWeight: '700',
wordWrap: 'break-word',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh'
}}>
<VStack spacing='24px'>
<div>
<p>Login Page</p>
</div>
<form onSubmit={onSubmit}>
<p>Username</p>
<Input onChange={(e) => {
setUsername(e.target.value);
}}/>
<p>Password</p>
<Input onChange={(e) => {
setPassword(e.target.value);
}}/>
<Button
colorScheme='blue'
type = "submit"
>
Submit
</Button>
</form>
</VStack>
</div>
</main>
);
}
And below is my relevant python code:
from fastapi import FastAPI, HTTPException, Depends, Request
from pydantic import BaseModel
from typing import List, Annotated
app = FastAPI()
models.Base.metadata.create_all(bind=engine)
class UserInfo(BaseModel):
username: str
password: str
....
@app.post("/frontend_testing")
async def create_user(req: UserInfo, db: db_dependency):
print(f"Username: {req.username}")
print(f"Password: {req.password}")
I’ve double checked my endpoint and my client request, and they seem to be properly setup for a post-request. Any help would be appreciated
Avik Samanta is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.