I’ve run into a problem with my React app after containerizing it. It works fine locally, but once I run it on Docker Desktop at port 3003, I receive a CORS error:
Access to XMLHttpRequest at 'https://nutrition-api.example.com/query?min_protein=5&max_protein=15' from origin 'http://localhost:3003' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000' that is not equal to the supplied origin.
hey there! sounds like a classic cors headache have u tried adding a proxy in ur package.json? somthin like “proxy”: “https://nutrition-api.example.com” might do the trick. if that doesn’t work, maybe look into using a cors middleware on ur backend. good luck!
I’ve encountered similar CORS issues when containerizing React apps. One solution that worked for me was setting up a nginx reverse proxy in the Docker environment. Here’s a basic nginx.conf you could try:
This setup forwards requests to your React app running on port 3003. You’d need to adjust your Dockerfile to include nginx and this configuration. It’s a bit more work upfront, but it gives you more control over your containerized environment and can solve tricky CORS issues like this. Remember to update your API calls to use relative URLs instead of absolute ones, so they go through the proxy.
The CORS error is likely due to the API server expecting requests from ‘http://localhost:3000’ while your app runs on port 3003. To fix this, you could adjust the API server’s CORS settings to include ‘http://localhost:3003’ as an allowed origin. Alternatively, consider configuring a reverse proxy in your Docker setup to redirect requests from port 3000 to 3003, or implement a backend proxy server to bypass CORS restrictions. If you are using create-react-app, adding a proxy field in package.json may offer a temporary solution until you handle production settings accordingly.