Search code examples
javascriptreactjsfunctionfetch

How to handle and redirect when blocked by CORS policy occurs in React application


I have a function that receives a result.text (this is a string from qr scan camera eg string:565650). When i have the result i saved in const productString, and then i make a get request with that string. If the response is ok i have my product and adding it to my checkout-bag,until that spot everything is working perfectly.

Also when i will scan a non product - qr code which means my result.text will not get a response i want to redirect the user in a 404 page. In addition i get Cors policy error.

enter image description here

I want after my scan if is not successfull to redirect the user in 404 page my code is below in that function.

  const handleScanResult = (result) => {
    setLoading(true);
    setProductString(formatString(result.text))
    fetchData(`${API_URL}/products/${formatString(result.text)}`)
      .then((data) => {
        handleAddMemo(data);
        setLoading(false);
        setOpenAddMemoDialog(true);
        handleClose();
      })
      .catch((ex) => {
        setLoading(false);
        console.log(ex,"ex")
      })
  };

Solution

  • Cors is a browser security mechanism, you cannot skip it... Well in fact you can try but you'll face issue, see Trying to use fetch and pass in mode: no-cors

    I recommand you to follow the rules. So either:

    • you server both app and api on the same host+port
    • you put a proxy like nginx to serve both on same host+port
    • you change your api to follow the needed rules, mostly headers and option method.

    There is a good explanation here : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    Here is a simple config file for Nginx if you want to give it a try

        server_name myapp.localhost;
    
        listen 80;
    
        location /api/myApp {
            proxy_pass http://127.0.0.1:15000;
            #Change 15000 to the API port you use
        }
    
        location / {
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_http_version 1.1;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_pass http://127.0.0.1:17050;
            #Change 17050 to the APP port you use
        }
    }