Full series: Building website with Nodejs - A post from my experience
Previous post: Install and Create basic structure for Nodejs website
package.json file
package.json
file is used for storing information about your application as
well as its dependencies. Usually, when managing your Nodejs application with
git, you should ignore the node_modules folder (which contains all the
dependencies). Instead, you can specify the library that your app use and then
let npm install it automatically for you with npm install
. Here is the default
package.json file generated by express
You don’t even need to specify the dependencies manually. When you install any
new package with npm, just add --save
flag so that npm will update the
package.json file automatically for you. For example
app.js file
This is the main file for starting your web app. Actually, there is not much thing to care about this file since express generated it automatically for you. For a full list of all Express’ APIs, please visit Express - api reference. In this post, I only discuss about some important ones.
Routing
Routing setting up in Express is straight-forward. You can define it inside your
app.js
file using the express app
object. For example
Usually, the handler function for each request has 2 input arguments (the third
one is next
, which will be discussed later in Middleware section). They are
req
and res
containing the information for request and response
respectively. In the above example, when you access /
, the handlerFunc1
will
response by rendering the index view (see the next section for View in
Express).
Views
Express support defining views using ejs or
jade template engine. I will choose ejs as the
demonstration since it has the same syntax with normal markup HTML. If you want
to use jade, it’s pretty similar for echoing the information sent from server.
The difference is just about the markup style. All views are stored in views
folder inside your web’s root directory with the file extension .ejs
. Back to
my previous example
After requesting to /
, the handlerFunc1
will be activated. Express will then
find the file index.ejs
inside the views
folder to render with an json
object { title: 'Express' }
. Below is an sample index.ejs file for this
playing those information
As you can see, to echo the property in the response json object, you can use
<%= propName %>
. You can also include server-side js code inside <% %>
. For
example
This style is pretty much the same with other server side languages like php, asp,..
If you use <%= %>
for HTML output, the markup tag will be escaped. To output
raw HTML, use <%- %>
Public resources
The resources (images, css, client-side javascript) is located inside public
folder. For example, to include the file public/css/style.css
inside your
page
Conclusion
That’s everything you need to know about the basics of Express. For the next post, I will give more information about the more advanced stuff of Express.