How to solve CORS issue in ReactJS
What is CORS?
Cross-Origin Resource Sharing (CORS) is a protocol that enables scripts running on a browser client to interact with resources from a different origin. This is useful because, thanks to the?same-origin policy?followed by?XMLHttpRequest?and?fetch, JavaScript can only make calls to URLs that live on the same origin as the location where the script is running. For example, if a JavaScript app wishes to make an AJAX call to an API running on a different domain, it would be blocked from doing so thanks to the same-origin policy.
How to resolve CORS issue?
To get rid of CORS issue you need to follow some following steps
1) Install http-proxy-middleware package
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
2) Create?setupProxy.js file under src folder - src/setupProxy.js and past below code in that file.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'https://siteurl1.com',
changeOrigin: true,
})
);
};
Referance -
Technical Lead at Indexnine Technologies
3 年Very useful