Want to overcome the CORS issue in ReactJS? You can set up a express proxy server using http-proxy-middleware to bypass CORS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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.
1 2 | const URL = `/proxy/${PATH}`; return axios.get(URL); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.