Enable CORS in React.js

                          CORS(Cross-Origin-Resource-Sharing) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at the origin access to selected resources from a different origin. The issue related to CORS is that the browsers will restrict CORS HTTP requests initiated from scripts for security purpose. CORS adds new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a browser. To avoid this CORS issue it must be configured in server to allow cross domain. You can also use a chrome plugin called CORS. This doesn’t really solve the problem.

If you cannot activate CORS in server create a middle ware. Use the below given code in app.js.

const express = require("express");

var cors = require('cors')

const app = express();

app.use(cors());

const { createProxyMiddleware } =require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({

    target:'http://localhost:8080/', //original url

    changeOrigin:true,

    //secure: false,

    onProxyRes:function (proxyRes, req, res) {

      proxyRes.headers['Access-Control-Allow-Origin'] = '*';

    }

}));

app.listen(5000);

This code will pass the request http://localhost:5000/api/xxx to original server and returns the result to client.

axios.get('http://localhost:5000/api/xxx', //proxy uri

{

   headers: {

      authorization: 'xxxxxxxxxx' ,

      'Content-Type':'application/json'

   }

}).then(function (response) {

   console.log(response);

});

Change client as shown above to call proxy and get data without issue.

Run your project and then run npm start.