Setting Up A Local Web Server With NodeJS & ExpressJS

Setting up a local web server with NodeJS is actually much easier than you would imagine. I was pretty shocked at how straight forward it is to do, so I thought I would share how to do it, really quickly!

Prerequisites

The code used in this tutorial will be entirely JavaScript & HTML, so, all you need in place is the following two points.

  1. Download NodeJsNote: for this tutorial, version 10.15.3 (MacOS) was used.
  2. Have an IDE handy, something like VS Code will be sufficient.

Setting up

First up we will need to set up a server file that node can execute and then act as a web server, serving files for HTTP requests just like any ordinary website. To do this, follow the next steps –

  1. Create a new folder, e.g. MyNodeApp
  2. Using the command line, navigate to this folder and run the npm init command to initialize your project

Installing Express

Next is a nice and simple step, open your terminal in the root folder and run

npm install express --save

Allow the files to download and then move to the next section

Configuring our Node server with Express

Step 1

Ok, no we have Express, we’re ready to start readying our server configuration.

  1. Create a new file named server.js in the root directory
  2. Add the following code in CodeBlock1 to the file.

CodeBlock1 server.js

const express = require('express')
const app = express()

// Start serv & listen on port 3000.
app.listen(3000, function () {
  console.log('Node listening on port 3000')
})

//Listen for get request on root url. eg. http://localhost:3000
app.get('/', function (req, res) {
  res.send('Woohoo, our homepage works!')
})

Step 2

Testing the server works…

  1. Now from the command line in the root folder, execute the following command, node server.js
  2. Then, with your browser, navigate to localhost:3000
  3. You should be served a blank screen with the message ‘Woohoo, our homepage works!’

Adding Views

We now need to add a templating engine, one in particular named EJS. EJS is enabled you to construct HTML code along with JavaScript variables that are passed in via the backend of your application. It’s highly similar to how Laravel works with its Blade views or ASP.NET works with Razor views.

Step 1

To add EJS, run the following command in the project root directory

npm install ejs --save

Step 2

Next, we need to instruct Node to use EJS as our template engine with the following line of code added to your server.js file –

app.set('view engine', 'ejs')

Step 3

EJS expects a view folder to present in the project directory, so we need to create one, and whilst we are there, we may as well create an index file too. So, create a new folder called views, and add a new file within the views folder but name this index.ejs

Step 4

Now we want to edit our server.js file so that it actually renders the index.js file when the root directory is accessed. To do this, edit your app.get listener function to return the following –

res.render('index');

rather than

res.send('Woohoo, our homepage works!')

So it should now look like this –

app.get('/', function (req, res) {
  res.render('index');
})

Step 4

Reboot the server by killing the instance of node and executing node server.js in your terminal again. There is a well-detailed answer on killing your node instances here on StackOverflow for multiple operating systems.

Step 5

Navigate to localhost:3000 again, and you should be presented with a beautiful blank page!

Step 6

Let’s add some HTML to the .ejs file so it actually looks like a proper page.

Add the following HTML to your index.ejs file –

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <!-- page content -->
    <p>Hello world!</p>
  </body>
</html>

Step 7

Reload your index page in the browser, and you should see a pretty white screen with the message Hello World!

Passing data from the backend to the client side

So, if we want to store data in our backend and pass it to the client side, how do we do it? It’s pretty straight forward, by using an object of data within the listener, and a snippet of code in the .ejs file we can pass data through.

Here is a very basic example –

Step 1

Firstly edit your app.get listener function, adding an object as a parameter to the render function.

server.js

//Listen for get request on root url. eg. http://localhost:3000
app.get('/', function (req, res) {
  res.render('index',  {welcomeMessage: "Welcome to my app."})
})

Step 2

Then add the following snippet to your index file, using the <%- %> syntax to allow us to specify variables.

index.ejs

<!-- page content -->
<p><%- welcomeMessage %></p>

Step 3

Kill your node server and re-run node server.js to start it up again. Navigate to your root URL in the browser and you should now see the welcome message within the page.

Summary

And that is it, a very basic NodeJS & ExpressJS web server. These two combined are perfectly capable of running a website with dynamic data. And it takes less than ten minutes to get it set up!

 

SHARE ON

The Author: Dan Englishby

Setting Up A Local Web Server With NodeJS & ExpressJS

You May Also Like

Leave a Reply

Your email address will not be published.