0

I'm trying to download data from my rest api using react app. Code works with url from example on this site https://pusher.com/tutorials/consume-restful-api-react, but not working when I'v changed url to my local backend app.

My code:

fetch("http://localhost:8080/AppRest/appController/getData?ID=1")
        .then(res => res.json())
        .then((data) => {
          alert(data)
          this.setState({ icos: data })
        })
        .catch(console.log)

My errors in web browser console:

[Error] Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
[Error] Fetch API cannot load http://localhost:8080/AppRest/appController/getData?ID=1 due to access control checks.
[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (getIcos, line 0)
[Log] TypeError: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.

I'v tested api and it prints json when I open page from url http://localhost:8080/AppRest/appController/getData?ID=1.

Below is my response header from backend app. This I can download when I connect to rest from web browser.

HTTP/1.1 200 OK
Content-Length: 65
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
X-Powered-By: Servlet/4.0 JSP/2.3 (Payara Server 5.2020.7 #badassfish Java/Oracle Corporation/1.8)
Server: Payara Server 5.2020.7 #badassfish
Bogus
  • 283
  • 1
  • 2
  • 13
  • This is a `CORS` issue as the error suggests, so you need to allow `http://localhost:3000` on the server-side to be able to make calls from your local development environment. – goto Jan 01 '21 at 14:17
  • Do I need to change something int backend or my react app? I'm sorry but I learning react from yesterday. And cors are something new for me. – Bogus Jan 01 '21 at 14:26
  • I'v tried to use mode: 'no-cors' but then I cannot obtain json from response, and response status is 0. – Bogus Jan 01 '21 at 14:27
  • This has to be done on the backend, setting `no-cors` on the client-side (`React`) won't make a difference. Look at the response headers from the `API` request, they should tell you which `origin`s are allowed, e.g. `Access-Control-Allow-Origin: https://example.com` – goto Jan 01 '21 at 14:30

1 Answers1

-2

Try to specify request options

let url = "http://localhost:8080/AppRest/appController/getData?ID=1";
let reqOptions = {
    method: "GET"
}

fetch(url, reqOptions)
    .then(response => {
        if (!response.ok) {
            console.log(response.statusText);
        }
        return response.json();
    })
    .then(data => {
        return data;      
    }).catch(err => console.log(err));
abnaceur
  • 252
  • 1
  • 2
  • 1
    It's a `CORS` issue that needs to be dealt with on the server-side, no sure why passing options to the `fetch` call would help. – goto Jan 01 '21 at 14:56