TestPro
TestPro

Reputation: 15

Not able to fetch data from node.js API hosted on localhost using ReactJs

I created an API http://localhost:3000/videos which gives following output:

[{"id":1,"name":"spark","url":"https://www.youtube.com/watch?v=cu2E0sSlWsY&t=1339s"},{"id":2,"name":"alia","url":"https://www.youtube.com/watch?v=IBYTVQ4Umdg"}] 

I am trying to fetch this using ReactJS using following code, but it doesn't fetch the data, instead it shows "Loading..." as I mentioned in my 'if' condition:

import React, {Component} from 'react';

class App extends Component {

    constructor(props){
      super(props);
      this.state = {
        videos: [],
        isLoaded: false,
      }
    }

    componentDidMount() {

      fetch('http://localhost:3000/videos')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true, 
          videos: json,
        })
      });
    }

    render() {

      var {isLoaded, videos } = this.state;

      if (!isLoaded) {
        return <div> Loading...</div>;
      }

      else {

        return (
            <div className="App">

                <ul>
                    {videos.map(video => (
                        <li key={video.id}>
                            Name: {video.name} 
                         </li>   
                      ))};               
                </ul>

            </div>
          )
        }
    }

}

export default App;

I tried to replace the url with http://jsonplaceholder.typicode.com/users and the code worked fine. It correctly fetched the name from the json. However, it doesn't work for my locally hosted APIs.

Upvotes: 0

Views: 1168

Answers (2)

Surya Reddy
Surya Reddy

Reputation: 47

If Your frontend and backend are not communicating there is 0.9 probability of CORS issue. Simply put his code on Your server side.

        app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

Hope this will help.

Upvotes: 0

walid sahli
walid sahli

Reputation: 416

maybe and almost its a CORS problem so in your backend install CORS by npm i cors --save-dev then use it in your server:

const cors = require('cors');
......
app.use(cors());
.......
app.listen(PORT , ()=> console.log('server on'))

Upvotes: 1

Related Questions