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}`);
});