This tutorial is written specifically for people who are planning to learn Nodejs. You may have programmed in PHP before, and willing to start your career in nodejs, then It will surely help you. I will try my best to explain you each thing in detail. We will learn about nodejs, expressjs, mongodb, mongoose, nodemon etc.
If you are new to programming then it is also fine. Grab some coffee and stay with me.
You can also download the full app.
The problem in learning NodeJS
Let’s discuss the problem first. Many of you tried to understand node. But you may have failed. The problem is not with the nodejs. Actually, you need to few things before writing your first code. That’s where most people leave it.
Another thing I see that some people are just afraid of the terminal. The reason is they actually never used one. In nodejs dealing with packages and installing them, everything is done in a terminal. So I will try to show you how you can easily manage your application.
Our Application
We are going to build a super duper simple application where people can save an article with a heading. In our application people also can view all the previous posted articles.
Things we need before starting
- Nodejs
- MongoDB
- A text editor
Installing NodeJs
First, go to Nodejs’s website and click on the download button. Click on the LTS version of the Node. The process is pretty simple. You just need to click next bunch of times. Nodejs will be installed in your system. The process is same for all the major operating systems.
Verify Nodejs Installation
Just open a terminal and type this code and hit enter. You will see your nodejs’s version by this.
By installing node, you will automatically get access to the node’s package manager npm. Npm comes with nodejs.
You can check your npm version with this following command. We will use
npm
a lot in building nodejs apps.
Install MongoDB
MongoDB is our server to save our data. The process is same as above. Visit https://www.mongodb.com/download-center and choose your operating system.
Run MongoDB
After installing MongoDB, we need to start our MongoDB. So open a new terminal (for windows open a command prompt window), and type
mongod
Keep this window open. We need to keep it open while we are developing our application.
Let’s get started with our Node Express App
We are done with our development setup. These things are mandatory to build a build a web application or a RESTful API with nodejs.
Now open another terminal window. Do not close the previous mongod window. You might now know, we are going to use an extremely popular nodejs web application framework, Expressjs.
Now we need to install express generator globally. To do this, run the following command
npm install express-generator -g
Now we can use the
express
command to generate our project.
Generating our project with express
Here we will tell express to generate a project named “article-app” with the templating engine “ejs”
express article-app --view=ejs
Now you will see a folder named article-app has been created. Now change your directory to this article app and run
npm install
to install all the dependency packages we need. You might need to run
sudo npm isntall
if you see permission denied message.
sandeep@emon:~/projects$ express article-app --view=ejs
create : article-app
create : article-app/package.json
create : article-app/app.js
create : article-app/public
create : article-app/public/stylesheets
create : article-app/public/stylesheets/style.css
create : article-app/routes
create : article-app/routes/index.js
create : article-app/routes/users.js
create : article-app/views
create : article-app/views/index.ejs
create : article-app/views/error.ejs
create : article-app/bin
create : article-app/bin/www
install dependencies:
$ cd article-app && npm install
run the app:
$ DEBUG=article-app:* npm start
create : article-app/public/javascripts
create : article-app/public/images
sandeep@emon:~/projects$ cd aricle-app
sandeep@emon:~/projects/article-app$ npm install
Are you tired?
You might feel tired now as to get started you need to do a lot of things. But that is fine. As you are just starting, it will be lot easier when you will grasp the concept behind nodejs applications.
After running
npm install
, you just installed all the dependencies mentioned in our
package.json
file.
This package.json file holds all the necessary information about our web applications. You can read more about this here.
The Folder Structure of the ExpressJs App
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.ejs
└── index.ejs
Let’s discuss the folder structure. The heart of our app is the app.js file. You will see another folder named node_modules. This folder contains all the dependency code of our application. You never need to open this folder while developing.
Run the application
To run our web application type
npm start
in the terminal and go to http://localhost:3000/ You should see a image like this one. If not then recheck all the previous steps.
Begin Coding
Open the folder article-app in your favourite text editor and begin coding. Open app.js file. It may seem quite heavy for you. But it is not.
var express = require('express');
With this require method, we are including express module into our project. If you open the package.json file, you will see
all the dependencies are listed there.
"dependencies": {
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"ejs": "~2.5.2",
"express": "~4.14.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
}
To properly include a dependency in your project, the module must be declared in your package.json file and then you should run npm install in your terminal. After that, we can require that module into our project.
Remember we just run one npm install, in the beginning, thus we installed all of our modules. It is now properly downloaded into our node_modules folder. Let’s install one package we need now to query and connect with our database MongoDB. The name of the package/module is mongoose.
Installing mongoose via terminal
Run this command in your terminal at the root of your project. Please open a new terminal at the root of your project.
sandeep@emon:~/projects/article-app$ npm install mongoose --save
We are telling npm to install mongoose package and also instructing to write it as a dependency into our package.json. If you now open package.json, you will notice that mongoose has been included there.
Lets modify our home page. Open views/index.ejs file. Paste the following code. I expect you that you know HTML.
<!DOCTYPE html>
<html>
<head>
<title>
<%= title %>
</title>
<link rel='stylesheet' href='/stylesheets/style.css' /> </head>
<body>
<h1>
<%= title %>
</h1>
<form>
<p> Name: <input type="text" name="name" placeholder="please type your name here" id="name"></p>
<p> Post: <input type="text" name="article" placeholder="article a text" id="article"> </p> <button id="submitBtn">Save</button> </form>
<script src="/javascripts/script.js"></script>
</body>
</html>
You can see we are including one JavaScript file and css file. So you go to public/stylesheets/style.css and add these below code. I know its looking extremely bad. You can do your own styling.
input {
padding: 1em;
margin: 1em;
}
button {
cursor: pointer;
padding: 10px;
border: none;
background-color: #67cc89;
color: white;
}
Now you should understand that anything in our public directory, we have it in our views files. We included our script file
<script src="/javascripts/script.js"></script>
So let’s open the public/javascripts folder, and create a file named script.js
Refresh the page at http://localhost:3000/, you should see like this below image.
Understanding app.js file
Actually, we are telling express to serve the public folder as our static assets in our app.js file. We are doing through this. The code is already written by express generator for you.
app.use(express.static(path.join(__dirname, 'public')));
Now we will connect with our database using mongoose
Connecting with MongoDB using mongoose
In the app.js file include these lines just after the requiring the body-parser
....
var bodyParser = require('body-parser');
// Require Mongoose and connecting with the MongoDB
var mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/article", function (err) {
if (err) {
console.log(err);
}
});
....
Remember that initially, we started our mongod. Now we are connecting with our local MongoDB. Generally, MongoDB runs on the port 27017.
mongodb://127.0.0.1:27017/article
Look at the connection string, with this, we are automatically creating one database named article.
Now we will create our Posts collection in our article database. A collection in MongoDB is similar to a table in SQL database.
Creating our Schema and Model using Mongoose
Using mongoose we are going to declare some rules which are called schema of our Posts collection.
Create models/Post.js and paste the following
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
article: String,
timestamp: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Post", PostSchema);
The code is quite self-explanatory. We are giving the structure to our collection. Each document of the Post collection will have three fields those are name, article, timestamp.
Creating our first REST API endpoint
Now we are going to create one end point to save our data into our database. To do that please open your routes/index.js file. Your index.js file should now like this.
var express = require('express');
var router = express.Router();
var Post = require('../models/Post'); /* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {
title: 'Express'
});
});
module.exports = router;
Let’s change the title of our home page. Just change index.js file to this.
var express = require('express');
var router = express.Router();
var Post = require('../models/Post');
// here we are saying to display the views/index.ejs file
// whenever we visit -> localhsot:3000/
// We can also send data as a second parameter of the res.render method
router.get('/', function (req, res, next) {
res.render('index', {
title: 'Article App'
});
});
module.exports = router;
Now if we refresh our page in the browser, we will not see any change. Because we have changed our code on the server side. So we need to restart our node server. You can do this by stopping the terminal (the terminal you ran npm start) by Ctrl+C
Then you need to run the server again by npm start. Now you should see that the tile of the app has been changed to “Article App”
Installing Nodemon using npm (Node Monitor)
It is irritating to restart our server each time when we make changes to our server code. So we are going to install a package called nodemon globally. Nodemon will intelligently restart our server whenever we make changes to it.
npm install nodemon -g
As we installed it with the global flag. The command
nodemon
is accessible throughout our system. Now we will start our server with nodemon.
Run the nodemon command in the root of your project
sandeep@emon:~/projects/article-app$ nodemon
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
You should see the result like this one. Now we can refresh our web page and work without restarting the server. the work will be done by nodemon.
Now add this code just after the home page get route. Please read the comments.
router.post('/save', function(req, res) {
// The data coming from the client is situated in the "req" object
// We can send or render data to the client using "res" object
// the data we got from the client will be in the req.body
// we also have properties of req like req.params and req.query
var data = req.body;
// lets create one document with requested data in the Post collection
// We alredy included the Post collection's model in the Top
// I am talking about this line -> var Post = require('../models/Post');
var post = new Post(data);
// Lets save the post
post.save(function(err) {
// If any error happens while saving,
// we will return saying an error message
if (err) {
return res.json({
error: true,
message: "Unable to save the post",
err: err
});
}
// otherwise perfectly saved
res.json({
error: false,
message: "Article Saved"
});
})
});
module.exports = router;
Basically, here we are getting the data from the client and trying to save to save to the Post collection of our article database.
Let’s make post request from client using Fetch
We are going to use HTML5 Fetch API to do our post request. We are not going to use old XLMHttpRequest.
To do this open, public/javascrpts/script.js and add the following code
function select(elem) {
return document.querySelector(elem);
}
var submitBtn = select("#submitBtn");
submitBtn.addEventListener("click", function (e) {
e.preventDefault();
var name = select("#name");
var article = select("#article");
// Simple error checking
if (name.value == '' || article.value == '') {
return;
}
// making our data ready
var data = {
name: name.value,
article: article.value
};
data = JSON.stringify(data);
// here we are using brand new in build fetch method to do a POST request
// Forget XHR :)
fetch("/save", {
method: "POST",
body: data,
headers: {
"Content-Type": "application/json"
}
}).then(function (res) {
return res.json();
}).then(function (res) {
console.log(res);
if (!res.error) {
name.value = '';
article.value = '';
}
alert(res.message);
window.location.reload();
})
});
Now go to your web page and refresh. Open the dev console. Write your name and article and hit the save button.
You should see a message saying
{error: false, message: "Article Saved"}
If not, then let me know in the comments section. I will surely help you out.
Congratulations!
You are able to send data from the client side. Your nodejs server getting that data from the client. You are saving it to the MongoDB. That is wonderful.
Let’s display the data. To do this we need little bit modification in routes/index.js file and in views/index.ejs file.
Serving the data from the server to the client
Open routues/index.js and change the according to the following code.
We will query the database in our get method of the homepage and send all the data to the client. We will do it before rendering. As I said earlier, in the render method, we can pass data as the second argument. That data will be available in our views/index.ejs file.
router.get('/', function(req, res, next) {
// We are querying the Post collection
// As we need all the data, we are passing a blank object {} for querying
Post.find({}, function(err, posts) {
res.render('index', { title: 'Article App', posts: posts });
});
});
Understanding EJS templating
Open
views/index.ejs file and modify it like below. You can write
EJS in between
<% // your ejs code %>
I chose EJS as the templating engine because you can write javascript here. You do not need to learn a separate templating engine to get started with nodejs.
Below we are checking if the posts data is available. If it is available then we looping over the content of the posts.
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<% if (posts.length > 0) { %>
<h3>Articles</h3>
<% posts.forEach(function (post) { %>
<p>
Name: <%= post.name %>
</p>
<p>
Article: <%= post.article %>
</p>
<hr>
<% }) %>
<% } %>
<form>
<p>
Name: <input type="text" name="name" placeholder="please type your name here" id="name"></p>
<p>
Post: <input type="text" name="article" placeholder="article a text" id="article">
</p>
<button id="submitBtn">Save</button>
</form>
<script src="/javascripts/script.js"></script>
</body>
</html>
Now if you refresh our web page, we can add our posts. Mine looks like this.
Yahoo!
Our app is complete. Though It is terribly bad looking but we learned a lot. Next steps to follow, please go to
ExpressJs Docs and Mongoose Docs to learn more. If you are stuck at any step, then let me know in the comments. I will try to update this article. Thank you for following this.
You can get the FULL SOURCE CODE AT MY GITHUB. Just clone the repo and run
npm install
and
npm start
to see it in working.
The post Step by step tutorial NodeJs ExpressJs MongoDB App for Beginners (April 2017) appeared first on Apply Head.