Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do front-end and back-end communicate?

So if I write an express app and I want to access it in the frontend , how do I do that?

If I write a frontend app, how do I access it in express?

Like for example i create a blog site, and I have a sign up form that I want to use AJAX on, so the user can sign up for newsletters and then the form hides, without having to reload the page. How would the front end and back end work to do that? Like code wise, do I need to import like we do routes in express? Etc..

This has me confused so any help is appreciated! Thanks!

2 Answers

Hello again!

So basically you make your routes in express. Eg app.get() app.post() etc. If we had a route like:

app.get('/api/main', (req, res) => {
  res.json({hi: "hi"});
});

If you were to go to http://localhost:port/main, it would return: {hi: “hi”}

So all you do is in your front end JavaScript with either Ajax or fetch api, you make an HTTP request to http://localhost:port/main/ and it would return the json data back and you could store that into a variable. Then, you could use that data inside the JavaScript object literal and insert it into the HTML in the front end JavaScript.

I hope this helps! If this does not make sense, please reply.

Thanks :)

Ok most of that makes sense, so what about when like you have a user login option and they go to login, you would get their login info from a database right?(if they already signed up) If so, would that be just by express handling all of that, or does front end work come in too ?

Express handles all of it.

Thanks for info! That clears it up a bit for me!