Hitting a wall on Voting App

Hi everyone !

I’ve completed all the API projects and I’m now stuck on the Voting App for 3 weeks (part time :p).

I managed to create most of the backend (mongodb base and express routes) just like for the API projects, but I’ve no idea how to relate that to the app pages.
I know I should use React or Angular (and would rather use React), but I can’t figure how to connect it to the api I created. The React official tutorial (TicTacToe) doesn’t seem to be relevant to what I need to do.

Can you provide me some hints to get me started ?

Thanks in advance

1 Like

With React, I use an npm package called ‘axios’ to do the requests to the api.

e.g. axios.get(’/users/’).then(function(users){ do something with the users })

with post requests, you would do axios.post(’/users/’,{object you are sending as body}).then…

If you are not using Redux, you can do the get requests in a component’s ‘componentWillMount()’ function to get the info that component needs.
Another strategy is to request a whole set of information in the top-level component and then pass it down as props to the other components.

Does that make sense?

I take if you use your API call in componentWillMount() that you save the information in state right?

That’s right. And if a child component needs it, just send it as props. No need to make an api request for each component.

Tank you for your replies.
I understand what axios does.
However I don’t understand How I could use React to link my backend to web pages.
Maybe React is a bit to hand to get for me right now. What are the easiest solutions to do that out there?

Create public folder in your server folder.
In your server file you should instruct express to serve static files from public folder:

app.use(express.static(path.join(__dirname, 'public')));

and also serve index.html if requested address doesn’t exist (put this just before app.listen...):
app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); });
In public folder put your regular react files: index.html, script, css.
Now when you go to your app’s url, you’ll get your react app.

To call backend from react do what @Marie000 said.


How would you write your web app without React? How would you create your web page if you didn’t write any of the back end and were just consuming a third party service (hint: remember your work with the weather forecast app)?

1 Like

Thank you very much for your help !

You finally made me understand how to serve pages that can get data from my backend !
It sounds like something obvious, but I couldn’t find that by myself…

Now it’s time to dive into React !

1 Like