I'm attempting a simple file upload with React and FastAPI but I can't figure out this 404 error. The API call works when I use the fastapi /docs#.
I expect the POST method to get a success response from the server but instead I'm receiving two errors:
My react code:
const [selectedFiles, setSelectedFiles] = useState<File | null>(null);
const handleSubmit = (event: SyntheticEvent) => {
const formData = new FormData();
if (selectedFiles) {
formData.append("file", selectedFiles, selectedFiles.name);
}
const formDataJSON = JSON.stringify(formData);
const requestOptions = {
method: "POST",
headers: { "Content-Type": "image/jpeg" },
body: formData,
};
fetch("http:/127.0.0.1:8000/files", requestOptions)
.then((response) => response.json())
.then((response) => {
console.log(response.json());
});
};
return (
<div>
<Stack
direction="row"
spacing={10}
justifyContent="center"
alignItems="center"
>
<form>
<fieldset>
<input
onChange={fileChangeHandler}
name="image"
type="file"
// multiple
accept=".jpeg, .png, .jpg"
/>
</fieldset>
<Button variant="contained" component="label" onClick={handleSubmit}>
Upload Dir 1
</Button>
</form>
<Button variant="contained" component="label" onClick={toggleDir2}>
Upload Dir 2
</Button>
</Stack>
</div>
);
};
My FastAPI code:
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
# App Object
app = FastAPI()
#
origins = ["http://localhost.tiangolo.com",
"https://localhost.tiangolo.com",
"http://localhos",
'http://localhost:3000']
app.add_middleware(
CORSMiddleware,
allow_origins=[origins],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"ping": "pong"}
@app.post("/files/")
async def create_file(file: bytes = File(default='image/jpeg')):
return {"file_size": len(file)}
It seems like the problem occurs because the post method is sending the request to "https://localhost:3000/127.0.0.1:8000/files". But I also can't find out where the "SyntaxError" is in the data.
Thanks for any help!