1

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:

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!

cgholt
  • 13
  • 2
  • Does this answer your question? [How to send a base64 encoded image to a FastAPI backend?](https://stackoverflow.com/questions/64788970/how-to-send-a-base64-encoded-image-to-a-fastapi-backend) – Chris Nov 19 '22 at 08:22

2 Answers2

0

You have defined your API endpoint as /files/ with a trailing slash, but your frontend is calling /files.

M.O.
  • 1,712
  • 1
  • 6
  • 18
0

In your react code, in the fetch part you are missing a '/' in the http. That is why its appending it to your react localhost. The correct code should like this:

fetch("http://127.0.0.1:8000/files", requestOptions)

Also, in your fastAPI code in the origins list code, you can just add the localhost of react

origins = [
    "http://localhost:3000",
]