-1

I have a front-end made with React js and a back end made with net core 2.0. Both run on localhost (localhost:3000 and 5001 respectively). All I'm trying to do is get the front-end to fetch some data:

fetch('https://localhost:5001/api/Login/' + this.state.username + '/' + this.state.password + '/')
    .then( results => {
        return results.json();
    })
    .then( data => {
        this.setState({
            jobTitle : data.jobTitle,
        });
    });

This method is called by a button, so whenever I click this button I get an error in the console.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/Login/matteo/baldini/. (Reason: CORS request did not succeed).

This happens in Firefox, on a machine running Windows 7.

Interesting to note that if I run the same exact code on my laptop running Mint it works just fine.

The API was made by running dotnet new webapi and I barely changed anything.

I've also tried to implement a number of solutions found in other questions and articles, as well as using the Cors everything on firefox but nothing works. I have no idea what to do at this point so any help is greatly appreciated.

Thanks everyone

Barbaldo
  • 72
  • 3
  • 11

1 Answers1

0

That happens because most browsers assume localhost:3000 and localhost:5001 as different hosts, therefore CORS header required in your API response in order to make communication possible.

In production potentially it will not be the case, if you will host it under the same hostname, but for test environment you may add

response.setHeader('Access-Control-Allow-Origin', '*');

in your API handler to allow access to your API from all origins.

WowPress.host
  • 133
  • 1
  • 6