Follow Us on Twitter

Node.js tutorial part 2; building a proper website

by Patrick Sinke on February 12, 2018 · 0 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)
app.use(express.static('public'));

// 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) {
   console.log(req.body);
   var transacties = mongoose.model('transacties');
   var transactie = new transacties(req.body);
   transactie.save(function (err) {
      if (err) {
         console.log(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
app.route('/transacties')
   .post(postTransacties)
   .get(getTransacties);

// 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:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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()
      };
      console.log(res);
         $.ajax({
            type: "POST",
            url: "/transacties",
            data: res,
            success: function (result) {
               console.log('succes');
            },
            error: function (jqXHR, textStatus) {
               console.log(textStatus);
            }
         });
      
   });
   });
	</script>
</head>
<body>
<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">  
                     </div>

              <label for="code" class="col-sm-3 col-form-label">Code</label>
                       <input id="code"  name="code" class="form-control code">  
                     </div>
<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">  
                     </div>
                        <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>
                    
 <div class="form-group-sm row">
 	<button class="addone" data-toggle="tooltip" span="" style="color:darkgreen" title="Opslaan">Save</button>
 </div>
 </body>
</html>

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!

Ratings:
VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)

{ 0 comments… add one now }

Leave a Comment

 

Previous post:

About Whitehorses
Company profile
Services
Technology

Whitehorses website

Home page
Whitebooks
Jobs

Follow us
Blog post RSS
Comment RSS
Twitter