How to overcome the CORS issue in ReactJS

后端 未结 7 1865
失恋的感觉
失恋的感觉 2020-11-28 06:30

I am trying to make an API call through Axios in my React Application.However, Iam getting this CORS issue on my browser. I am wondering if i can resolve this issue from a c

7条回答
  •  佛祖请我去吃肉
    2020-11-28 06:51

    Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

    A simpler way is to use express-http-proxy

    1. run npm run build to create the bundle.

      var proxy = require('express-http-proxy');
      
      var app = require('express')();
      
      //define the path of build
      
      var staticFilesPath = path.resolve(__dirname, '..', 'build');
      
      app.use(express.static(staticFilesPath));
      
      app.use('/api/api-server', proxy('www.api-server.com'));
      

    Use "/api/api-server" from react code to call the API.

    So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

提交回复
热议问题