How to solve CORS issue in ReactJS

How to solve CORS issue in ReactJS

What is CORS?

No alt text provided for this image


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 -


Sohan Patil

Technical Lead at Indexnine Technologies

3 年

Very useful

要查看或添加评论,请登录

Shyam Hajare的更多文章

  • How to convert HTML to pdf in NodeJS

    How to convert HTML to pdf in NodeJS

    Follow the following steps to convert HTML to pdf Step 1 - install the pdf creator packages by the following command $…

    4 条评论
  • Fizz Buzz Algorithm Implementation

    Fizz Buzz Algorithm Implementation

    Fizz Buzz is a very simple programming task, asked in software developer interviews. Write a program that prints the…

  • Upgrade Magento from 2.2.3 to 2.2.5

    Upgrade Magento from 2.2.3 to 2.2.5

    Following are the steps for upgrading Magento 1) php bin/magento maintenance:enable 2) composer require…

  • Create Magento 2 Theme

    Create Magento 2 Theme

    The following steps required to add a new theme to the Magento system - Create a directory for the theme under…

  • Create Configurable Product Using CSV - Magento 2

    Create Configurable Product Using CSV - Magento 2

    1) Create Simple Product CSV ( Please Refer sample CSV ) 2) Map Simple Product to Configurable ( Please Refer sample…

    2 条评论

社区洞察

其他会员也浏览了