Basic server using Node.js + Express
We’ll make a simple server app, that displays a message, using Node.js & Express JS, as you would use in a simple landing page. We’ll go step by step, as this is a tutorial for noobs, made by a noob.
Installing Node.js
Go to Node webpage and download the proper installation file according to your OS and follow the instructions. To check if Node is correctly installed, type:
$ node -e "console.log('Hello World! Running Node.js '+ process.version)"
Starting our server app
So, we have Node in our computer; let’s start our server!. First, we’ll create the package.json file using npm. What for? npm’s documentation helps us understand:
This file affords you a lot of great things:
1. It serves as documentation for what packages your project depends on
2. It allows you to specify the versions of a package that your project can use usingsemantic versioning rules
3. Makes your build reproducable which means that its way easier to share with other developers.
To create it, in your working directory type:
$ npm init
You’ll be asked to fill some data, like the name of the project, it’s version, and more.
On success, you’ll find a package.json file that will contain some information about our app, and it’s dependencies (Of course, at this point we have no dependencies).
Now, let’s create the file that will contain the source code to our app:
$ touch app.js
In the app.js file, we’ll write the code from our app. Let’s start by the obvious. Paste the following code to the file:
console.log("Hello World!");
And now, run the server and see what happens:
$ node app.js
Installing Express
Express JS is a web framework for Node.js, designed for building web pages & apps. According to Wikipedia:
“It is the de facto standard server framework for node.js”
To install Express, in your working directory, type:
$ npm install express --save
By using the ‘ — save’ parameter, the file package.json is automatically updated with the new dependency, go check it out.
To use Express in our app.js file, you have to require it:
var express = require('express');
var app = express();
This piece of code will allow us to use Express features, using the variable ‘app’. For example, we will now declare a route. Routing refers to the definition of application endpoints (URIs) and how they respond to client requests; basically, how to respond to a client when he access to a certain page or route of our server (‘/’, ‘/about’), using a certain method (GET, POST).
For example, if you access http://localhost:5000/ using your browser, you are performing a GET request to the port 5000 of the ‘localhost' server, specifically, to the ‘/’ route. To make our server app respond to such a request, we’ll use Express’s ‘get’ method, and it’s callback function (The ‘response’ object and it’s ‘send’ method in the code below).
app.get('/', function (request, response) {
response.send("Hello World!");
});
This piece of code means that whenever we receive a GET request to the ‘/’ route, we will respond to the client by sending him a “Hello World!” string.
Finally, we have to tell our app to wait for connections in some port. We’ll use the 5000.
app.listen(5000, function(){
console.log("app.js listening on port 5000")
})
And we’re good to go! Let’s run our app:
$ node app.js
Then in your favorite browser, access http://localhost:5000/. Magic!
What now?
You have a server now! Research a bit, add some more code lines, get a nice front-end page and you could have a serious web app running! There are millions of things you can do with this.
To start, a good thing you could do is telling your server to render a HTML page instead of sending a “Hello World” string when accessing ‘/’ right?
Also, another thing you could do is making our server capable to handle more routes; in a real world scenario, to make it respond with an ‘index.html’ file when accessing ‘/’ and ‘about.html’ when accessing ‘/about’, and so on.
Finally, we could also redirect a request to any other route (‘/qwerty’) to our ‘/’ route, to handle unexisting routes and typing error from the user.
Render an HTML using Express
To start, we’ll create an ‘index.html’ file. To separate the server files from the HTML files, we’ll place the html file in a folder called ‘views’.
<!-- views/index.html -->
<html>
<head>
<title>Node.js + Express server</title>
</head>
<body>
<h1>Node.js + Express server</h1>
<p>Welcome to my server!</p>
</body>
</html>
We’ll modify our ‘app.js’ file, so that whenever the server receives a request to the ‘/’ route, it provides the ‘index.html’ file. This is done by using the ‘sendFile’ method of the ‘response’ object from the callback function of Express’s ‘get’ method. To correctly send the HTML file, we must provide the full path to the webpage file to ‘sendFile’, using the ‘__dirname’ variable, which is the directory where our app.js file resides.
app.get('/', function (req, res) {
res.sendFile(__dirname+'/views/index.html');
});
Adding more routes
We could inmediatly add a new route, to manage requests to the ‘/about’ route. This should be simple by now, since it’s the same as the above.
app.get('/about', function (req, res) {
res.sendFile(__dirname+'/views/about.html');
});
Make sure to create the ‘about.html’ file. Here’s mine.
<!-- views/about.html -->
<html>
<head>
<title>Node.js + Express server</title>
</head>
<body>
<h1>About</h1>
<p>This server was made using Node.js + Express on February 13, 2016.</p>
</body>
</html>
Redirect unwanted requests to ‘/’
If you run the server and access a unmanaged route, you’ll get an ugly message. Try it out http://localhost:5000/qwerty .
To manage this, one simple thing we could do is to redirect any unwanted route to our root route ‘/’. This is done by telling the ‘get’ method to manage any route with ‘/*’, and telling it to redirect the response to the ‘/’ route.
app.get('/*', function (req, res) {
res.redirect('/');
});
Since the ‘app.js’ file is read from top to bottom, we have to make sure that this is the last route in the source code; elsewise, the ‘/about’ route would also be redirected to ‘/’.
Run the server and check it out!
Final Words
With 10~20 lines of code, we have our basic server! Sure, it lacks A LOT but it’s a start. I’ll try to cover the use of middleware, error management and some other cool stuff you can use with Node in other posts.
The code
Just in case, you can find the code from this post @Github