83

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.

8
  • 6
    this 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? Commented Sep 21, 2017 at 7:06
  • You need to enable server side. See IIS7 example here: enable-cors.org/server_iis7.html Commented Sep 21, 2017 at 7:11
  • i am third party i am using only API whis is implemented on AWS server. Commented Sep 21, 2017 at 7:12
  • i need to know where i append CORS code in my file Commented Sep 21, 2017 at 7:14
  • 4
    CORS 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. Commented Sep 21, 2017 at 7:24

10 Answers 10

48

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:

response_object.header("Access-Control-Allow-Origin", "*");
response_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  1. Config NGINX for proxy_pass which is explained here.

  2. Bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)

  3. Bypass the cross-origin-policy with URL bellow(only for development)

"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
  1. 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/",

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);
        });
});
Sign up to request clarification or add additional context in comments.

1 Comment

For (6), here's a more elaborated answer.
19

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();
});

6 Comments

Does 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?
In my case of running Next.js front-end server + Express API back-end server running on same machine, instead of "*" I did "localhost:[next.js port]" to fix this. Didn't need the second res.header line.
For me I added this code and it still throws error anyways :( But only on some phones
Setting these headers like this complete removes the security which CORS was invented to provide. Proceed with caution.
I added cors on my backend but still I get this cors policy error on my react app
|
13

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.

2 Comments

This doesn't answer how to fix the problem in react.js, this is just a band aid
Disabling CORS on your browser will not really solve this problem for your application, as it only applies to your machine.
8

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")]

Comments

5

You just have to add cors to your backend server.js file in order to do cross-origin API Calls.

const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());

2 Comments

i'd also add, that app.use(cors()) have to be added right after init of the app variable
Oh right, Okay added lol.
4

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 }));

Comments

4

It took me quite a long time to understand what was going on here. It seems I did not realize CORS is something that should be configured on the API side you are doing the request at. It was not about React, at least in my problem. All other answers did not work for me possibly as I have a different API.

Some solutions for Python based APIs (FastAPI/Flask)

If you are doing your requests from React to FastAPI, here are the instructions for it: https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware.

If you are doing requests from React to Flask, this is probably what you need: https://flask-cors.readthedocs.io/en/latest/

After configuring the API, just leave the absolute URLs in place (like http://127.0.0.1:8000/items)

Comments

2

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

1 Comment

I keep reading package.json proxy setting is ignored completely in production builds
2

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();
});

1 Comment

This is for development only, and it is not recommendedd
1

Adding proxy in package.json or bypassing with chrome extension is not really a solution. Just make sure you've enabled CORS in your server side before you have registered your routes. Given example is in Node.js and Express.js. Hope this helps!

    app.use(cors())
    app.use('/users', userRoutes)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.