You also
need mongodb to do this tutorial: https://www.mongodb.org/downloads
Step 1 – Set up a node.js
workspace with express
1. First,
you have to make a directory for your new app, like C:\nodeapp. You can either
do this in Windows Explorer or through command line.
In Windows
Explorer you just have to make the folder you want to have your app inside.
Through
command line (cmd.exe in Windows), you could use this command:
C:\> mkdir nodeapp
2. You have to point the command line to the folder where you keep your project:
C:\> cd nodeapp C:\nodeapp>
3. You have
to install all the dependencies that we need in this app. The most important
one is express, which is an add-on to node.js that makes it much easier to
select what is on different places on your website. It also makes a template
for a node app, so you do not have to make all the files you need yourself. Installing
dependencies for node.js is done through something called npm (= node package
manager). (The –g in the command says that the express-generator shall
auto-install). You install express through
command line this way:
C:\nodeapp> npm install -g express-generator
4. Use the express-generator to make a template for your app, where you
change “testapp” with the name you want to use for your app:
C:\nodeapp> express testapp
If everything goes well you end up with a document structure like this:
I will explain some of the files later.
5. You have to install all the dependencies that your new app needs. Do
this in the terminal:
C:\nodeapp> cd testapp C:\nodeapp\testapp> npm install
You can test if everything went fine by starting the app. To start your
current app you have to start it through command line:
C:\nodeapp> cd testapp C:\nodeapp\testapp> npm start
The terminal will now output something like:
> testapp@0.0.0 start /home/ubuntu/workspace/node/testapp > node ./bin/www
If everything went fine, you would see the following in your browser:
To stop your app again, go
back to your terminal and press Ctrl+C. Congrats, you have set up a node.js
workspace!
Step 2 – Set up a mongodb
database
The main file of every node.js app is called “package.json”. This is a
json file, which means that it has a special structure. Json is a file format
where you can store data in columns, and is the format that mongodb use to
store data. Your “package.json” probably looks like this:
{
"name": "testapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0"
}
}
First on
every line with data, you have a string that is the name of the variable, then
comes a colon, and afterward is the value of the variable. The first important
value here is "scripts", which has the variable "start".
The value of "start" says which script is the main script. The main
script is "node ./bin/www", which is a server script. The script
basically starts a server, and sends all the requests to your "app.js"
script, and that is where I write most of the code.
What is also important in the "package.json" file is the "dependencies" category. The category lists everything we need to get the app running. As you see, the express add-on is successfully implemented. However, we miss the mongodb add-on that is necessary to get the app communicate with the database.
For
security reasons, when people register their username and password, it is usual
to hash the password. Hashing is a one-way encrypting algorithm, which cannot
be done back again. Therefore, even if hackers get control over our database,
they will not be able to get the passwords. To being able to hash passwords in
node.js, you have to have the additional crypto add-on.
To install
the mongodb and crypto dependencies, use the terminal again:
The --save
part in the end of the line tells npm that it should update the "package.json"
file with mongodb and crypto as new dependencies. If you refresh your "package.json"
file both mongodb and crypto should be listed:
{
"name": "testapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"crypto": "0.0.3",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"mongodb": "^2.1.7",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0"
}
}
The mongodb
is now installed!
However,
you also need to update the require list in the app.js file. Open the app.js
file and you would see that the first lines is probably something like this: Open
the app.js file, and look at the requires in the start:
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser');
Our node.js app does also require mongodb and crypto in order to work, therefore add the
following lines:
var crypto=require("crypto"); var mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient;
The mongodb.MongoClient line is because you need the MongoClient part of the mongodb add-on to connect and send requests to the mongo database.
Step 3 – Setting up the app.js file
I want for
simplicity, have the whole app inside the "app.js" file. Therefore you
don’t need the routes folder or the files in the folder. You can therefore
delete the next following lines:
var routes = require('./routes/index'); var users = require('./routes/users');
The next
lines are necessary. This is what they do:
var app = express();
This means that this web application is a express app. The variable app will now get all the requests to the website.
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');
The next two lines says that we are using the jade engine to make HTML pages, and that the jade files is in the views folder. If you look inside the views folder, there are some .jade files there. I will explain the jade engine later.
// uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
If you put an favicon.ico file in the public folder, you can remove the comment slashes from the second line. The line is just for inserting a icon on your web page.
app.use(logger('dev'));
This line says that the web application shall make a log of what is happening on the app. This will make it easier to see what eventual errors are, but is not necessary for the app to work. I would, however, recommend that you keep it.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
This is for getting parameters like username or comments that the users are submitting to the page.
app.use(cookieParser());
We use this so that we can read the users' cookies. This is necessary, because we use the cookies to see whether someone is logged in.
app.use(express.static(path.join(__dirname, 'public')));
This line says that everything inside the public folder are static files, which means that if someone go into the URL of these files, they are getting the plain file. This is useful for having a place to store CSS or client-side JavaScript files.
app.use('/', routes); app.use('/users', users);
You should delete the lines over, because I am going to have the whole app inside “app.js”. Anyway, what the lines do is that if you get a get request to the sites “/” or “/users”, the request is forwarded to the index.js or the users.js file. To divide the web application like this makes larger applications more structured, but for small web applications it is easier to just use the “app.js” file.
The rest of
the lines beneath are just the error messages that your web application will show when
there are errors. It is not very important, but keep them as they show the errors
in your web application when they occur.
You can now continue on part two on the project: http://allrounddeveloper.blogspot.no/2016/02/nodejs-express-and-mongodb-beginner_23.html
If there are any questions or suggestions of things I could have done better, please use comment section below.
You can now continue on part two on the project: http://allrounddeveloper.blogspot.no/2016/02/nodejs-express-and-mongodb-beginner_23.html
If there are any questions or suggestions of things I could have done better, please use comment section below.


Ingen kommentarer:
Legg inn en kommentar