How to overcome the CORS issue in ReactJS

后端 未结 7 1855
失恋的感觉
失恋的感觉 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:58

    You can set up a express proxy server using http-proxy-middleware to bypass CORS:

    const express = require('express');
    const proxy = require('http-proxy-middleware');
    const path = require('path');
    const port = process.env.PORT || 8080;
    const app = express();
    
    app.use(express.static(__dirname));
    app.use('/proxy', proxy({
        pathRewrite: {
           '^/proxy/': '/'
        },
        target: 'https://server.com',
        secure: false
    }));
    
    app.get('*', (req, res) => {
       res.sendFile(path.resolve(__dirname, 'index.html'));
    });
    
    app.listen(port);
    console.log('Server started');
    

    From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.

    const URL = `/proxy/${PATH}`;
    return axios.get(URL);
    

提交回复
热议问题