Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - Fetching API data via React

I am building my first web application with a django backend and react frontend.

I cannot accomplish to fetch the data and print them as an output on my page. I have no idea why fetching dummy api data from sites like https://jsonplaceholder.typicode.com/todos is possible, but my own api data not.

Here is a little code snippet where I get the error in my HTML-Inspector: JSON.parse: unexpected character at line 1 column 1 of the JSON data

const [todos, setTodos] = React.useState([]);
    const url = "http://127.0.0.1:8000/article/";
    const proxyurl = "https://boiling-tor-92690.herokuapp.com/";

    React.useEffect(() => {
      fetch(proxyurl + url,{
        method:'GET',
        headers:{
            'Content-Type':'application/json'
        }

      })
        .then(res => res.json())
        .then(todos => setTodos(todos))
        .catch(err => console.log(err.message));
    }, []);
    
  
    return (

      <div>

          {todos.map(e =>{
              return <h2>{e.email}</h2>
          })}
            

      </div>
    );

Here I had to use a heroku-proxy to fix a CORS-Error

I also tryed it with a functional component and could afford to get my API-Data in my Console but I still got the JSON Parse Error:



    componentDidMount() {             
        var self = this;
        fetch('http://127.0.0.1:8000/article/')
          .then(function(response) {
                  return response.json()
          })
          
          .then(function(data) {
            self.setState({ 
                data 
            }, 
            
            () => 

            
            console.log(self.state));


          });
      }


Do someone know how to fix this ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you get an error message that tells you something you expect to be JSON isn't… then look at the value of what you are trying to parse. It will probably give you a big clue.


The server running at boiling-tor-92690.herokuapp.com is not going to access your computer when you ask it to fetch http://127.0.0.1:8000/article/. It will access its own 127.0.0.1:8000 server.

… which will probably not exist, so you'll get an error message, so you don't get JSON, so you'll get the error you got.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...