-1

I had an issue posing to an external backend from my REACT app due to a CORS error.

Access to XMLHttpRequest at 'https://testsecureacceptance.cybersource.com/pay' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I decided on this solution https://stackoverflow.com/a/60908929/14287707 that uses nodejs as a middleware .The external endpoint I am posting to is "https://testsecureacceptance.cybersource.com/pay" which upon success redirects to "/checkout" that opens a checkout page. My nodejs is running on localhost:5000 while my REACT is running on localhost:3000 . I am convinced there's smt I am missing given its my first nodejs app and would love an extra pair of eyes to guide here. So localhost:5000 gets hit and returns a status code 302 redirect. But /checkout still gives me the error - "Access to XMLHttpRequest at 'https://testsecureacceptance.cybersource.com/checkout' (redirected from 'http://localhost:5000/') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested"

REACT

export default function Absa() {

  const [result, setResult] = useState(null);

  const [checkout, setCheckout] = useState(null);

  const {uuid} = useParams();

  const absa = async () => {
    try{
      let res = await axios.get(`${process.env.REACT_APP_PAYMENT_URL}/signed_data/${uuid}`)

      setResult(res.data);
    } catch (e) {
      console.log(e)
    }
  }
  ;

  useEffect (() =>{
    absa()
  },[])

const qs = require('qs');

  const postData = (e) =>{
    e.preventDefault();
    axios.post('http://localhost:5000',

  qs.stringify({ ...result }),
  
  ).then(response => {

    if (!response.data){
      throw Error("ERROR");  
    }
    let responseHtml = response.data;
    
   //open the new window and write your HTML to it
    var myWindow = window.open("", "response", "resizable=yes");
    myWindow.document.write(responseHtml);
   
  })
  .catch(error => console.log(error));
  
  };

node js

const express = require('express'); //Import the express dependency
var cors = require('cors')
const app = express();              //Instantiate an express app, the main work horse of this server
app.use(cors());
const port = 5000;                  //Save the port number where your server will be listening

const { createProxyMiddleware } = require('http-proxy-middleware');
app.use('/', createProxyMiddleware({ 
    target: 'https://testsecureacceptance.cybersource.com/pay', //original url
    changeOrigin: true, 
    //secure: false,
    onProxyRes: function (proxyRes, req, res) {
       proxyRes.headers['Access-Control-Allow-Origin'] = '*';
    }
}));


app.listen(port, () => {            //server starts listening for any attempts from a client to connect at port: {port}
    console.log(`Now listening on port ${port}`); 
});
siderra
  • 51
  • 7
  • _"checkout still gives me the CORS error"_... what error, exactly? – Phil May 10 '22 at 07:35
  • Why are you trying to bypass it in the first place? – super May 10 '22 at 07:42
  • @Phil I have edited the question & added the error – siderra May 10 '22 at 07:50
  • @super I have edited and added the initial error – siderra May 10 '22 at 07:52
  • Ok, so your browser it getting redirected to `https://testsecureacceptance.cybersource.com/checkout`. Naturally you get a CORS error. What's the confusion? And again... why are you trying to do this in the first place? I fail to see a reason this would ever be usefull unless you're trying to impersonate the target site and hiding it to the user. Is that the goal? – super May 10 '22 at 08:15
  • @super the CORS errors are as a result of the browser hitting 'https://testsecureacceptance.cybersource.com/pay' directly. So the goal is to hit the nodejs middleware(isnt a browser so it wont get the CORS error) which in turn hits the endpoint – siderra May 10 '22 at 08:44
  • No. The CORS errors are a result of fetching `https://testsecureacceptance.cybersource.com/checkout` after being redirected there. As the error message clearly states. – super May 10 '22 at 11:46
  • Browser posts to `localhost:5000`, which is proxied to `https://testsecureacceptance.cybersource.com/pay`. That return a 302 redirect to `https://testsecureacceptance.cybersource.com/checkout`. Now the browser posts to `https://testsecureacceptance.cybersource.com/checkout` and gets a CORS error. – super May 10 '22 at 11:48
  • @super thanks this totally makes sense now.So I need to proxy the second browser post as well ? Coz thats exactly what I was avoiding. The browser posting directly to any of the endpoints – siderra May 10 '22 at 13:21
  • 1
    IMO you need to stop trying to "work around" something that is clearly not meant to be worked around and use it as intended instead. But as you keep insisting on not giving any more information on what you are actually trying to achieve here I don't see any point in trying to answer your question either. – super May 10 '22 at 13:26
  • @super when the Broswer posts to the endpoints I get CORS error like I attached on the question. However when the proxy posts to the endpoints I dont get the CORS error. So I am trying to proxy the requests to the proxy so that it does the postings to the endpoints which will not bring the CORS error – siderra May 10 '22 at 14:02
  • Yes. But why are you trying to access cross-site content from the browser? It's not allowed, and for good reason. – super May 10 '22 at 14:12

0 Answers0