'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)
Solution 1:
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.
Solution 2:
Use the google Chrome Extension called Allow-Control-Allow-Origin: *. It modifies the CORS headers on the fly in your application.
Solution 3:
Fix Without Using External Proxy or Chrome Extension
CORS should be enable in server side! if you can not activate it on server (for example using external API) create a middleware React -> Middleware -> Orginal Server
.
-
Create a Node.js project (Middleware) and use below 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 will pass the request http://localhost:5000/api/xxx
to original server (for example http://localhost:8080/api/xxx
), and returns the result to client.
-
Change client (React) to call proxy and get data without CORS error (you only need to change the port in url):
axios.get('http://localhost:5000/api/xxx', //proxy uri { headers: { authorization: ' xxxxxxxxxx' , 'Content-Type': 'application/json' } }).then(function (response) { console.log(response); });
-
run node project
node app.js
and react projectnpm start
.
Solution 4:
I had the same problem. the other answers are correct but there is another solution. you can set response header to allow cross-origin access. according to this post you have to add the following codes before any app.get call:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
this worked for me :)
Solution 5:
//install cors using terminal/command
$ npm install cors
//If your using express in your node server just add
var cors = require('cors');
app.use(cors())
//and re-run the server, your problem is rectified][1]][1]
**If you won't be understood then see below image**
https://i.stack.imgur.com/Qeqmc.png