Follow Us on Twitter

Node.js tutorial part 2; building a proper website

by Patrick Sinke on February 12, 2018 · 6 comments

Your first fully functional Node.js application

In the first part of this tutorial we set up a development environment. As you have noticed there, the core of a Node.js application is a server side Javascript file. You will be editing this file a lot and along the while it will grow accordingly.

I think the first step you will take, is change your code so that node.js serves a proper website. This can be an entirely new site, but without much effort an existing one too.

First things first. npm is the tool we used for creating a first application. When installing packages with npm, you have different options for installing them. With npm -g <packagename> you install global (system-wide) packages, without the -g packages are installed into the current directory/project.

When we’ re on it , install MongoDB on your system. We’re going to use it in our application as a database. Installation is pretty straightforward on most systems, this site is an excellent starting point.

There are a number of npm packages that are of huge value when creating node.js applications, but the choice is enormous. The following list (in no particular order) of packages is especially invaluable:

  • path
  • express
  • mongoose
  • body-parser

Let’s see how we use this in a simple but functional Node.js application. Create a new directory for your project and run

npm init

The wizard is pretty self-explanatory. Now we install the necessary npm packages. Install them using these commands:

npm install express --save
npm install express-session --save
npm install body-parser --save
npm install mongoose --save

To make things easy for you, here’s a code snippet you can paste into the index.js at the root of your project:

// initiate express middleware
const express = require('express');
const app = express();

// assign the directory 'public' for storing static 
// files (e.g. HTML and CSS)

// enable the parsing of request bodies and 
// simplified handling of JSON content
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

// initiatie Mongoose for MongoDB connectivity
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rodeo', {
   keepAlive: true,
   reconnectTries: 10

// define a schema for a mongoDB collection
const Schema = mongoose.Schema;

var transactieSchema = new Schema({
   userName: {type: String},
   transactieDatum: {type: Date},
   code: {type: String},
   aantal: {type: Number},
   bedrag: {type: Number}
   //  _id: false
   {collection: 'transacties'});
mongoose.model('transacties', transactieSchema);

// Do some neat forwarding of the root of your site 
// to a default file
app.get('/', (req, res) => res.sendfile('index.html'));

// a function for handling a post request
postTransacties = function (req, res, next) {
   var transacties = mongoose.model('transacties');
   var transactie = new transacties(req.body); (err) {
      if (err) {

      return res.json({value: 'hello'});


// a function for handling a get request
getTransacties = function (req, res, next) {
   var transacties = mongoose.model('transacties');
   transacties.find({}, function (err, data) {
      return res.json(data);


// routing for post and get on the /transacties url

// finally, let's fire up a webserver at port 3500
app.listen(3500, function () {
   console.log('listening on *:3500');
   module.exports = app;

This is not the best practice in terms of maintainability (it’s better to keep your database, router and controller-middleware in different files), but it will demonstrate everything you need for a full-fledged Node.js application including posting and retrieving data.

Final thing you need is a new directory “public”. Create an index.hml there with this contents:

<script src=""></script>
<script type="text/javascript">
	 $(document).ready(function () {
 $('body').on('click', '.addone', function () {
      var res = {
         userName: $('.naam').val(),
         transactieDatum: new Date(),
         code: $('.code').val(),
         aantal: $('.aantal').val(),
         bedrag: $('.bedrag').val()
            type: "POST",
            url: "/transacties",
            data: res,
            success: function (result) {
            error: function (jqXHR, textStatus) {
<div class="form-group-sm row">
                        <label for="Naam" class="col-sm-3 col-form-label">Naam</label>
                       <input id="naam"  name="code" class="form-control naam">  

              <label for="code" class="col-sm-3 col-form-label">Code</label>
                       <input id="code"  name="code" class="form-control code">  
<div class="form-group-sm row">
                        <label for="aantal" class="col-sm-3 col-form-label">Aantal</label>
                       <input id="aantal" type="number"  name="code" step="1" class="form-control aantal">  
                        <label for="bedrag" class="col-sm-3 col-form-label">Bedrag</label>
                       <input id="bedrag" type="number"  name="bedrag" step="0.01" class="form-control bedrag">  
 <div class="form-group-sm row">
 	<button class="addone" data-toggle="tooltip" span="" style="color:darkgreen" title="Opslaan">Save</button>

Now, go to the root of your project and type

node index.js

And when you point your browser to http://localhost:3500 a simple input form will be presented.

If you want to check if everything works as expected, fill in the form, press Save and go to http://localhost:3500/transacties . A JSON document will be displayed with all the records you saved.

That’s all. Now you have a fully working skeleton from where you can start building your enterprise website in Node.js!

Node.js tutorial part 2; building a proper website, 5.0 out of 5 based on 1 rating
VN:D [1.9.22_1171]
Rating: 5.0/5 (1 vote cast)

{ 6 comments… read them below or add one }

7PABGQW3 December 16, 2019 at 7:52 pm
Brother Printer Driver is Unavailable window 10 April 13, 2020 at 9:28 pm

I really appreciate this post. It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it! Good post….thanks for sharing.. very useful for me I will bookmark this for my future needs. Thanks.


Brother Printer Manual Feed Error April 15, 2020 at 5:59 pm

I have been reading your posts regularly. I need to say that you are doing a fantastic job. Please keep up the great work.


Dell Printer Error Code 016-302 April 15, 2020 at 11:01 pm

I learn some new stuff from it too, thanks for sharing this…
Dell Printer Error Code 016-302


Sharathamohan May 21, 2020 at 5:01 pm

Useful information . Thank you for sharing


Business Essay Writing Services June 23, 2020 at 7:06 am

Business coursework writing services are essential for business assignment writing services and Business Essay Writing Services seekers.


Leave a Comment


Previous post:

Next post:

About Whitehorses
Company profile

Whitehorses website

Home page

Follow us
Blog post RSS
Comment RSS