icon-arrow icon-check icon-mail icon-phone icon-facebook icon-linkedin icon-youtube icon-twitter icon-cheveron icon-download icon-instagram play close close icon-arrow-uturn icon-calendar icon-clock icon-search icon-chevron-process icon-skills icon-knowledge icon-kite icon-education icon-languages icon-tools icon-experience icon-coffee-cup
Werken bij Integration & Application Talents
Blog 12/02/2018

Node.js tutorial part 2; building a proper website

Website

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('transactiesransactieSchema);

// 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*: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>
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

	 $(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);
            }
         });
      
   });
   });
	
</head>
<body>

                        Naam
                         
                     


              <label for="code" class="col-sm-3 col-form-label">Code</label>
                       <input id="code"  name="code" class="form-control code">  
                     </div>

                        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>
                    
 

 	Save
 

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

Geen reacties

Geef jouw mening

Reactie plaatsen

Reactie toevoegen

Jouw e-mailadres wordt niet openbaar gemaakt.

Geen HTML

  • Geen HTML toegestaan.
  • Regels en alinea's worden automatisch gesplitst.
  • Web- en e-mailadressen worden automatisch naar links omgezet.

Wil je deel uitmaken van een groep gedreven en ambitieuze experts? Stuur ons jouw cv!