At the last Node post, we have put our app to run, but, if we want to serve others pages, implement others features in our app?
We must decouple the html code from our JS files too!
So, let’s start!
Weird term, but, is what it is! For example, unlike Ruby, that is a opinionated language (“the Rails Way”, that tells you to do what they think it’s a right way to do), Express is a framework that let you free to do on your way.
If you don’t know nothing about routes, at Express website, you can learn routing basics!
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
You can also use an Express Generator, but, at this moment, I want to do it by hand!
So… let’s do it!
Refactoring our app for the 1st time
This is what our app is look like:
Yes… I move the side bar to the right. Why? I feel more confortble this way! hehehehe “Visual Studio feelings” 😉
Typographic ligatures are when multiple characters appear to combine into a single character. Simplistically, when you type two or more characters and they magically attach to each other, you’re using ligatures that were supported by your OS, your app, and your font.
And, I liked!
Returning to our first refactoring! Focus, Camilo!!!
Well, to handle the routes, I put a new file at the project: app.js and it’ll be the new starting point of tha application.
At app.js, I required the Express Module, that returns a function and, at sequence, I run the returned function creating the app object!
Unlike Node, I don’t need to create a server, etc., I just need to call the listen function, passing the port that it’ll be listening and a callback.
As callback, I simply log a message.
At browser, when I navigate to http://localhost… Error! Why?
Well… there is no route configured! Let’s do it.
The syntax, according Express API documentation is:
app.METHOD(path, callback [, callback …])
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are
app.put(), and so on. See Routing methods below for the complete list.
So, for the get of the main page:
And, hitting F5 at browser we get…
And this is the basic of Express! Next post we’ll talk about EJS!