title: Puzzling error with FastAPI's CORS middleware
body: <p>I'm new to FastAPI. I am having problems posting images. The console says it's a <code>CORSMiddleware</code> problem:</p>
  <pre><code>Access to XMLHttpRequest at 'http://localhost:8000/images' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  </code></pre>
  <p>I have also set it to allow everything, but it's still not working.</p>
  <pre><code>app = FastAPI()
  app.add_middleware(CORSMiddleware,
                     allow_origins=[&quot;*&quot;],
                     allow_credentials=True,
                     allow_methods=[&quot;*&quot;],
                     allow_headers=[&quot;*&quot;])
  </code></pre>
  <p>My only conclusion is that fastapi and CORS are not importing at the top in main.py correctly. Why is this happening even though they are installed?</p>
  <p><a href="https://i.stack.imgur.com/uEkch.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uEkch.png" alt="enter image description here" /></a></p>
  <p><a href="https://i.stack.imgur.com/QwoCX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QwoCX.png" alt="enter image description here" /></a></p>
  <p>Here is a minimum workable example. The frontend is in React.js. It's coming in as props from a file reader. In this specific instance there is only one image being uploaded.</p>
  <p>React FormData:</p>
  <pre><code>
  const [image, setImage] = React.useState(null);
  const [src, setSrc] = React.useState(null);
  
  export default function PostImage(props) {
  const selectedImage = (img) =&gt; {
      setImage(img);
    };
  
  async function PostData () {
  let formData = new FormData();
  formData.append(&quot;files&quot;, image);
  let response = await axios.post(&quot;http://localhost:8000/images&quot;, formData);
  setSrc(`http://localhost:8000/images/${response.data.id}.jpeg`);
  }
  return(
  &lt;img src={src} alt=&quot;&quot; /&gt;
  )
  }
  </code></pre>
  <p>Here is the image validation in Python FastApi:</p>
  <pre><code>from typing import List
  from sqlalchemy.orm import Session
  
  # import dependencies
  import os
  from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
  from typing import Optional
  from uuid import uuid4  # this is for creating image ids
  import PIL
  from PIL import Image as pil_image  # this is to read and save images
  
  from database.database import get_session
  from models.images import Image
  
  router = APIRouter()
  
  @router.post(&quot;&quot;, response_model=ReadImage)
  def create_image(caption: str = Form(...), tags: str = Form(...), files: Optional[List[UploadFile]] = File(None),
                   session: Session = Depends(get_session)) -&gt; Image:
  
   extension = files.filename.split(
          &quot;.&quot;)[-1] in (&quot;jpg&quot;, &quot;jpeg&quot;, &quot;png&quot;, &quot;JPEG&quot;, &quot;PNG&quot;)
   if not extension:
          raise HTTPException(status_code=415,
                              detail=&quot;Only accepts jpg/jpeg and png. Maybe your file extension is not specified or erroneous.&quot;)
  
   try:
          im = pil_image.open(fp=files.file)
          im = im.convert('RGB')
  
          extension = im.format in (&quot;JPEG&quot;, &quot;JPEG 2000&quot;, &quot;PNG&quot;, None)
  
          if not extension:
              raise HTTPException(status_code=415,
                                  detail=&quot;Only accepts jpg/jpeg and png. Your file seems to have the correct extension, but is in the wrong format, truncated, or corrupted1.&quot;)
  
          # 2a validation through verify method of pillow library
          im.verify()
          im.close()
  
          # 2b verification through simple transpose method which would uncover truncated images
          im = pil_image.open(fp=files.file)  # is this correct?
          im = im.convert('RGB')
          im.transpose(method=PIL.Image.ROTATE_180)
  
  uuid = str(uuid4().hex)
  
      # save pillow image object
      im.save(os.path.join(&quot;images&quot;, uuid + &quot;.jpeg&quot;), &quot;JPEG&quot;)
      im.save(os.path.join(&quot;images&quot;, uuid + &quot;.png&quot;), &quot;PNG&quot;)
  
      # create a new image instance
      db_image = Image(id=uuid, caption=caption)
      # register image in session
      session.add(db_image)
      # save changes in database
      session.commit()
      # reload image from database
      session.refresh(db_image)
  </code></pre>
  <p>The error on the server-side occurs at &quot;extension&quot;. &quot;'Files' does not have a 'filename'&quot;, presumably because no file is being sent.</p>