3

I have a problem fetching data using React with TypeScript from a webapi (.Net Core 3.0.100). The webapi project has an endpoint, http://localhost:5000/api/values. I can browse to this URL directly in Chrome and see the data, I can also access the endpoint succesfully in Postman.

In my root/[React-app]/App.tsx folder I have the following code:

  state = {
    values: [],
  };


  componentDidMount() {
    axios.get('http://localhost:5000/api/values').then((response) => {
      console.log(response);
      this.setState({
        values: [
          { id: 1, name: 'Value 101' },
          { id: 2, name: 'Value 102' },
        ],
      });
    });
  }

When I go to localhost:3000 on my host the console cannot access "values", the status is (failed) and gives the following error: GET http://localhost:5000/api/values net::ERR_FAILED

When I expand the error the first row is showing an error in "dispatchXhrRequest" under xhr.js

There is a red underlining under request.send(requestData)

  request.send(requestData);
  });
};

I am totally lost, I can access any other endpoint, such as jsonplaceholder.typicode.com/posts using the same code above, but the not http://localhost:5000/api/values

How can this problem be fixed? I have tried for 2 days and I cannot solve it so need help from the community.

Project details:

React with TypeScript React v17.0.1 .Net Core 3.0.100 3 class libraries (Application, Domain, Persistence) 1 webapi (API)

I have extensively checked other questions and they seem to either have a response to older versions of React and/or .Net Core or they do not solve this particular problem.

Nick Smith
  • 37
  • 4

1 Answers1

0

In Startup.CS I had to add the following to the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)     
services.AddCors(opt => 
                {
                     opt.AddPolicy("CorsPolicy", policy => 
                     {
                         policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
                     });
                });

And the below added to the Configure method:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 app.UseCors("CorsPolicy");

Thanks to ABOS for linking to a question that had a hint to the solution.

Nick Smith
  • 37
  • 4