I'm using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.
-
5this is not a react issue. This is a security measure implemented by browsers. Are you the owner of the API, or is it a third party api? – Paul Fitzgerald Sep 21 '17 at 07:06
-
You need to enable server side. See IIS7 example here: https://enable-cors.org/server_iis7.html – Niels Steenbeek Sep 21 '17 at 07:11
-
i am third party i am using only API whis is implemented on AWS server. – Shweta Singh Sep 21 '17 at 07:12
-
i need to know where i append CORS code in my file – Shweta Singh Sep 21 '17 at 07:14
-
1CORS has to be enabled on the server where the API is running on. You cannot enable this in your client code. If the API supports CORS the browser will do the request. – t.niese Sep 21 '17 at 07:24
-
Possible duplicate of [How to overcome the CORS issue in ReactJS](https://stackoverflow.com/questions/43462367/how-to-overcome-the-cors-issue-in-reactjs) – bennygenel Sep 21 '17 at 07:52
8 Answers
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
![](../../users/profiles/3324556.webp)
- 11,259
- 12
- 45
- 57
![](../../users/profiles/9640654.webp)
- 155
- 1
- 3
-
2Does this mean if my front end is deployed somewhere else I dont need to change anything on the Frontend. These headers are supposed to be added to the backend REST API headers? – Ahmed Aug 12 '19 at 21:18
-
In my case of running Next.js front-end server + Express API back-end server running on same machine, instead of "*" I did "http://localhost:[next.js port]" to fix this. Didn't need the second res.header line. – Mark Jackson Feb 10 '20 at 23:28
-
For me I added this code and it still throws error anyways :( But only on some phones – GaddMaster Jul 30 '20 at 09:40
there are 6 ways to do this in React,
number 1 and 2 and 3 are the best:
1-config CORS in the Server-Side
2-set headers manually like this:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass which is explained here.
4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)
5-bypass the cross-origin-policy with URL bellow(only for development)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-use proxy
in your package.json
file:(only for development)
if this is your API: http://45.456.200.5:7000/api/profile/
add this part in your package.json
file:
"proxy": "http://45.456.200.5:7000/",
and then make your request with the next parts of the api:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
![](../../users/profiles/10606346.webp)
- 1,117
- 12
- 21
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
![](../../users/profiles/868533.webp)
- 2,638
- 28
- 28
![](../../users/profiles/1651733.webp)
- 454
- 2
- 8
-
32This doesn't answer how to fix the problem in react.js, this is just a band aid – Code Wiget May 16 '19 at 14:25
-
3Disabling CORS on your browser will not really solve this problem for your application, as it only applies to your machine. – Andrew Zaw Nov 23 '19 at 17:58
I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.
in the request, you must set in header Content-Type:
Axios({
method: 'post',
headers: { 'Content-Type': 'application/json'},
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order,
}).then(function (response) {
console.log(response);
});
and in backend (Asp .net core API) u must have some setting:
1. in Startup --> ConfigureServices:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
2. in Startup --> Configure before app.UseMvc() :
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
3. in controller before action:
[EnableCors("AllowOrigin")]
![](../../users/profiles/11158366.webp)
- 107
- 3
on the server side in node.js I just added this and it worked. reactjs front end on my local machine can access api backend hosted on azure:
// Enables CORS
const cors = require('cors');
app.use(cors({ origin: true }));
![](../../users/profiles/1944063.webp)
- 4,139
- 1
- 32
- 23
Suppose you want to hit https://yourwebsitedomain/app/getNames from http://localhost:3000 then just make the following changes:
packagae.json :
"name": "version-compare-app",
"proxy": "https://yourwebsitedomain/",
....
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
...
In your component use it as follows:
import axios from "axios";
componentDidMount() {
const getNameUrl =
"app/getNames";
axios.get(getChallenge).then(data => {
console.log(data);
});
}
Stop your local server and re run npm start. You should be able to see the data in browser's console logged
![](../../users/profiles/6159885.webp)
- 221
- 3
- 11
-
I keep reading `package.json` `proxy` setting is ignored completely in production builds – dylanh724 Mar 26 '21 at 05:15
You just have to add cors to your backend server.js file in order to do cross-origin API Calls.
const cors = require('cors');
app.use(cors())
![](../../users/profiles/9023714.webp)
- 432
- 4
- 5
Use this.
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
![](../../users/profiles/1402846.webp)
- 8,605
- 144
- 77
- 113
![](../../users/profiles/14314227.webp)
- 1
- 1
- 1