1

I am using axios to get data from an API, I am trying to do something very simple and I have done it before. I can see on the console that my request was made but I cant output the data or a console.log() message.

componentDidMount() {
    axios.get("https://dog-api.kinduff.com/api/facts")
    .then( response => {
        console.log("Facts: ")
        this.setState({DogFact:response.data})
    })
    .catch( err => {
        this.setState({error:err.data.message})
    })
}

The response from the api is an object with an array.

{facts["fact written here"]}

It should be very simple but If I try that:

axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
    console.log("Facts: ", response) //This wont show up on the console
    this.setState({DogFact:response.facts[0]}) //This wont work.
})

I dont really understand what might be wrong. Could someone maybe help me out?

3
  • 1
    Its a cors issue most probably due to which the promise goes into .catch which is why you don't see the console Commented Feb 3, 2019 at 18:08
  • You are right. I am getting a network error but there is no other information. When I check the console I can see the request and the correct response. That is why I got confused. Commented Feb 3, 2019 at 18:10
  • 1
    1.if you have control over the backend server then you can set "Allow-Control-Allow-Origin": "your-website-address.com" or wildcard "Allow-Control-Allow-Origin": "" 2.you can use chrome extension [*Allow-Control-Allow-Origin][1] (but each browser may need to install this plugin to work on it) [1]: chrome.google.com/webstore/detail/allow-control-allow-origi/… Commented Feb 3, 2019 at 18:45

1 Answer 1

1

add this line in package.json

"proxy": "https://dog-api.kinduff.com/api/"

then in your axios call change it to this:

axios.get("/facts")
.then( response => {
    console.log("Facts: ", response) 
    this.setState({DogFact:response.facts[0]})
});
Sign up to request clarification or add additional context in comments.

1 Comment

So that means that the problem was really CORS and using proxy is a way to overcome it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.