Setting Up a New “Express” App Using Node.js and Goorm IDE
The objectives of this exercise is to create an app in Node.js that has everything I need to copy and paste stuff from in the future to quickly get setup. If you want to know how to get setup with a development environment to give some of this stuff a go then have a little read of Working With the Command Line in Goorm IDE (Node.js) – Backend Web Development.
The first thing is to setup routes to various directories in the app.
- When you go to “/” you get a message saying “Home Page”.
- When you got to “/join” you get a message saying “Join us”.
- When you got to “/game” you’ll get a message that says “Start game”.
If you’ve not done it yet at all I would suggest you took a look at nodemon which is a really cool package that resets the server every time you save a file so you don’t have to restart the server every time you make a change. That and (because of the -g in the command below) once it’s installed it’ll be in all of your future environments.
npm install -g nodemon
At the start of any “express” project, the very first thing that needs to happen is we need to initialise npn. Doing this will create our package.json file (that contains all of the metadata for the app).
npm init
This is the first time I’ve done any “back end” development and thought I’d take some notes as I go along. Firstly a new folder was created in goorm IDE called “firstExpressApp” and in that a new JavaScript file called app.js. While in that folder, “install npm express –save” was also typed into the command line to install express into the new app environment.
Then, when we install any packages into the project folder, we use the –save syntax at the end of the install prompt.
npm install express --save
If you’re already lost then why not have a little read of Working With the Command Line in Goorm IDE (Node.js) – Backend Web Development?
In the app.js file that we created the first thing to do is connect the express package to our file and to do that we use the following syntax.
var express = require("express");
app = express();
Then we setup a listener so that our server can tell which URL the visitor is trying to access. This is done using a function called app.listen() which takes two arguments, first is the server port and the other is what needs to be returned; in this instance, just to prove the listener is working, I used console.log().
app.listen(3000, function() {
console.log('Server listening on port 3000');
});
Once the listener was setup I could begin to write the function that displays the different sentences depending on what URL is visited.
app.get("/", function(request, response){
// request is an object that contains all of the
// information that was gathered when the request
// was made.
response.send("Home Page!");
});
For now the send() function is used to send the data back and in this instance we’re just sending a string of text.
app.get("/join", function(request, response){
response.send("Join Us!");
});
app.get("/game", function(request, response){
response.send("Play Now!");
});
Once all that is added to the app.js file we can start the server by launching the app (typing in node app.js or simply nodemon into the command line) – we should get a message returned to the console saying “Server listening on port 3000”.
If so we can now find our development link (called the “Running URL and Port” sattings) and visit it in our browser.
When we visit our server we find the file extensions that we specified (“/game”, “/join” and “/”) but when we visit one that we’ve not yet visited we get a message saying something like “Cannot GET /games” or whatever filename we typed in. To fix that the following (similar to the previous 3) can be used.
app.get("*", function(request, response){
response.send("ERROR!");
});
Now when we visit a directory that we haven’t set a listener up for we’ll be shown the text “ERROR!”
// This last bit needs to be placed below all of the others otherwise it will override them and all URL’s will give an ERROR message including the ones we declare.
Some more examples I learned / used that display content based on the structure of the URL.
app.get("/r/:subsection", function(request, response){
response.send("Long!");
});
app.get("/r/:subsection/comments/:id/:title",
function(request, response){
response.send("Longest!");
});
Coding challenges
As part of the course I’m doing we were set a challenge to display dynamic information based on what animal appeared in the URL. To achieve this, an object was created called sounds that contained the sounds each animal makes.
app.get("/speak/:animal", function(request, response){
var animal = request.params.animal.toLowerCase();
var sounds = {
cow: "Moooo",
dog: "Woooof",
cat: "Meoow",
fish: "Blooop"
}
var sound = sounds[animal];
response.send("The " + animal + " Says '" + sound + "'");
});
The name of the animal was retrieved from the directory in the URL and on that page the name of the animal in question was displayed as well as the sound that animal makes.
The next challenge was to display the word in the first directory of the URL “num” (the second value in the URL) number of times.
app.get("/:message/:amt", function(request, response){
// Create the variables that are needed
var amt = Number(request.params.amt);
var message = request.params.message;
// The variable that constructs the string
var reply = "";
for (var i=0 ; i<amt ; i++){
reply += message + " ";
}
// The send method can only be used once as for
// each request, there is only one response.
response.send(reply);
});
A bare bones express app template
var express = require("express");
var app = express();
app.get("/", function(require, response){
response.send("Whoop!");
});
app.listen(3000, function() {
console.log('Server listening on port 3000');
});
Sending HTML through our route
If we want to send through HTML to our page (instead of just having some text) then we need to install “ejs” package (ensuring we type –save to save the package to our dependencies list – will only work if we have typed in the command npm init which should be the first thing we do in a new environment).
npm install ejs --save
The reason we use EJS (which stands for embedded JavaScript) is because it allows us to have dynamic templates (in terms of pages on a website or app).
As in the examples above, if we wanted to send through some HTML (instead of just text) then we would the .render method (instead of .send as before).
app.get("/", function(require, response){
response.render("<h1>Can now render HTML thanks to ejs!</h1>");
});
This isn’t very efficient however as it would be hard to code in a web page template onto one line of code so EJS allows us to “call” an HTML file and then populate that file with JavaScript. The way EJS works is the files that we call need to be saved inside of a folder called “views” and need to be given the file extension of .ejs. When the page is loaded in the browser the EJS package will automatically look for the “views” folder and get whatever file has been declared in the routing function.
var express = require("express");
var app = express();
app.get("/:test", function(request, response){
var message = request.params.test;
response.render("html.ejs", {name: "BOB"});
});
// The file needs to be created and populated with HTML
app.listen(3000, function() {
console.log('Server listening on port 3000');
});
The above is a simple little setup that returns HTML to the /test directory on the app/site/whatever it is. The HTML that will be returned is shown below.
<h1>No WAY I can see <%= name %> </h1>
The JavaScript goes in between the <%= %>. The example above will render a HTML page that has an h1 tag on it that says “No Way I can see BOB”.
Creating a loop using EJS
To create a loop, rather than usinf the <%= %> command (which will render whatever the output of the js is) we use the <% %> command (missing out the “=” sign – meaning we’re sending through logic).
An example of a program that would display a for loop in Node.js is as follows:
JavaScript file (stored in root of project folder as per package.json file)
var express = require("express");
var app = express();
app.get("/:test", function(request, response){
var message = request.params.test;
response.render("html.ejs", {name: "BOB"});
});
// The file needs to be created and populated with HTML
app.listen(3000, function() {
console.log('Server listening on port 3000');
});
HTML content that is rendered by the JavaScript file (stored in “project folder”/views)
// Note: The best way to do this is to write out your loop as usual and then wrap any JavaScript lines in the <% %> EJS wrappers.
<h1>No WAY I can see <%= name %> </h1>
<% for(var i=1 ; i<=name.length ; i++){ %>
<ul>
<li>Item <%= i %> here <%= name %></li>
</ul>
<% } %>
As horrendous as it is, you’ll get the following output from the above code.
