1

I have a dummy FastAPI app, which works fine on my mac, but doesn't when I host it on a VM using docker. The login page sends an ajax request to /login endpoint, which I have written as http://localhost:8000/login, which works on my mac, but when I access the app on VM, by typing its ip address in my browser, I get this error:

Access to XMLHttpRequest at 'http://localhost:8000/login' from origin 'http://[the IP address of my VM here]' has been blocked by CORS policy.

How can I resolve this?

scott_m
  • 151
  • 2
  • 11
  • That depends on how you're building your JavaScript application. Usually you provide the active base URL as an environment variable (for example through vite) when you build the JavaScript application for its production environment. If you're doing it manually, you'll have to use the correct URL when you deploy to production, for example by having a configuration file that indicates the correct base URL in both environments. – MatsLindh Mar 25 '23 at 16:42
  • Have you tried to use `0.0.0.0` as host in docker? And don't you forget to map the corresponding ports? Maybe you will also need to set up hosts in cors. – Blind Kai Mar 25 '23 at 16:44
  • @BlindKai yes, the docker command is `CMD ["uvicorn", "medi_app:app", "--host", "0.0.0.0", "--port", "8000"]` – scott_m Mar 25 '23 at 16:51
  • @scott_m try to set CORS middleware and set `*` wildcards to check if CORS work correctly: https://fastapi.tiangolo.com/tutorial/cors/?h=cors. Also, please check this issue: https://github.com/tiangolo/fastapi/issues/5086 – Blind Kai Mar 25 '23 at 16:54
  • Please have a look at this [related answer](https://stackoverflow.com/a/73963905/17865804) as well. – Chris Mar 25 '23 at 18:59

0 Answers0