skip to Main Content

I’m getting a CORS error from a dockerized ReactJS app. When I tested it locally it worked fine. But after I dockerized it and pushed it to Docker Desktop as port 3003, it gave an error:

Access to XMLHttpRequest at ‘https://keto-diet.p.rapidapi.com/?protein_in_grams__lt=15&protein_in_grams__gt=5’ 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.

Here is my React code:

const options = {
  method: "GET",
  url: "https://keto-diet.p.rapidapi.com/",
  params: {
    protein_in_grams__lt: '15',
    protein_in_grams__gt: '5'
  },
  headers: {
    "X-RapidAPI-Key": "myapikeyishere",
    "X-RapidAPI-Host": "keto-diet.p.rapidapi.com",
  },
};
const Products = () => {
  const [products, setProducts] = useState([]);
  const ketoRecipes = async () => {
    const response = await axios.request(options);
    setProducts(response.data);
  };

  useEffect(() => {
    ketoRecipes();
  }, []);

Here is the docker desktop
enter image description here

What should I do to avoid the CORS issues? Thanks

2

Answers


  1. If you don’t control the API server-because it’s a third-party API- you can try to use proxy.

    I assume the server is expressjs

    const express = require('express');
    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    const app = express();
    
    app.use(
      '/api',
      createProxyMiddleware({
        target: 'https://keto-diet.p.rapidapi.com',
        changeOrigin: true,
      })
    );
    
    app.listen(3003, () => {
      console.log(`Proxy server is running on port ${PORT}`);
    });
    

    to call this API, you can use minimalized url like

    const options = {
      method: "GET",
      url: "/api/", // here
      params: {
        protein_in_grams__lt: '15',
        protein_in_grams__gt: '5'
      },
      headers: {
        "X-RapidAPI-Key": "myapikeyishere",
        "X-RapidAPI-Host": "keto-diet.p.rapidapi.com",
      },
    };
    
    
    Login or Signup to reply.
  2. Add the following in the options

    headers: {
        "Content-Type": "application/json"
    },
    withCredentials: true,
    credentials: "include"
    

    This will allow the json format file transfer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search