OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

React Client request tp Fast API Backend returning 405 Method not allowed

  • Thread starter Thread starter Avik Samanta
  • Start date Start date
A

Avik Samanta

Guest
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

Code:
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:

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
<p>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:<a href="https://i.sstatic.net/bq1B4oUr.png" rel="nofollow noreferrer"><br />
405 Error:</a></p>
<p>However, when testing out json inputs on the FastAPI endpoint ui, it works fine:<a href="https://i.sstatic.net/YjTyIV3x.png" rel="nofollow noreferrer"><br />
Success:</a></p>
<p>Below is my frontend page with the form and on submit async funcs:</p>
<p>page.tsx</p>
<pre><code>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>
);
}
</code></pre>
<p>And below is my relevant python code:</p>
<pre><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}")
</code></pre>
<p>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</p>
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top