How to get data from NodeJs backend?

How to get data from NodeJs backend?
0

#1

Hello Campers,

I try to fetch data from the backend into the frontend but I have some problems. In my server.js I’m connected to a mongo store but I don’t know how the pass this data into the front-end.

In my Layout-Component i want to fetch the data
class FetchDemo extends React.Component {
constructor(props) {
super(props);

    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios.get(`url to fetch from`)
      .then(res => {
        const posts = res.data.data.children.map(obj => obj.data);
        this.setState({ posts });
      });
  }

  render() {
   ....
}

#2

With mongoose and promises (haven’t used vanilla mongod much):

app.get('/url to fetch from', (req, res) => {
  ModelName.find({}).then(data => res.send(data);
}

#3

You might like this awesome Node.JS Plugin I found called Socket.IO. It’s insanely easy to transfer information between the client and the server.


#4

SocketIO is good for real time communication. I don’t believe it would be practical to deliver large amounts of data through web sockets, correct me if I’m wrong, but I think AJAX still wins.


#5

True, but I’m comfortable with Socket.IO, and it’s really best for communications between your own pages and their server. If you want to set up an AJAX server, I recommend Express for sending back info through your own API. I usually use Express to serve Socket.IO pages.