Ranjitha R
Ranjitha R

Reputation: 31

React JS - No 'Access-Control-Allow-Origin' header is present on the requested resource. Cross Origin Resource Error

I'm making an API call (Running on another domain) using Fetch in a React Web app. I am getting the error Following error.

Access to fetch at '--------API URL---------' from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have also read several answers on Stack Overflow about the same issue, titled "Access-Control-Allow-Origin" but still couldn't figure out how to solve this. I don't want to use an extension IN Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.

My code looks like this:

{
        return fetch('-----------API URL--------',
        {   method:'GET',
            mode: 'cors',
            headers:{
                'Access-Control-Allow-Origin':'*'
            },
        })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson.ALLORDERSRX);
            this.setState({
                isLoading: false,
                dataSource: responseJson.ALLORDERSRX,
            }, function(){
                
            });
        })
        .catch((error) =>{
            console.error(error);
        });

    }

Upvotes: 2

Views: 43096

Answers (2)

Mariel So GuZa
Mariel So GuZa

Reputation: 88

The probable reason why you're getting the CORS error message is that the API has a different origin than where you are doing the requests from, so you need to tell the API that it is okay to accept requests from other origins (it's better to specify from what other origins instead of saying that from everyone).

I had a similar issue, I tried changing the header from the part of the front-end from where I was doing the calls and then also tried changing the controller but what worked for me was changing the Start.cs file of the API project and add the following... (I recommend trying it first in localhost and then deploying the changes where you actually have the API)

public class Startup
{
    private readonly string _MyCors = "MyCors";
    .
    .
    .
    public void ConfigureServices(...)
    {
        .
        .
        .
        //Under your services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy(name: _MyCors, builder =>
            {
                //for when you're running on localhost
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
                .AllowAnyHeader().AllowAnyMethod();


                //builder.WithOrigins("url from where you're trying to do the requests") this should be specified to get it working on other environments
            });
        });
    }
    public void Configure(.....)
    {
        //before the app.UseAuthorization & app.UseEndpoints
        app.UseCors(_MyCors);
    }
}

Upvotes: 0

Saurabh Mistry
Saurabh Mistry

Reputation: 13699

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://api.liveconnect.in/backend/web/erpsync/get-all-orders?data=dbCode=UAT04M%7Cidx=100%7CuserId=6214%7Cres_format=1'; // site that doesn’t send Access-Control-*
fetch(proxyurl + url).then((resp) => resp.json())
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log(error);
  }); 

found from here :No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Upvotes: 5

Related Questions