<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mahesh Bhanushali on Medium]]></title>
        <description><![CDATA[Stories by Mahesh Bhanushali on Medium]]></description>
        <link>https://medium.com/@bhanushalimahesh3?source=rss-215e1cd64ac1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Qw1pqfKNSSbCagZye7J9ag.jpeg</url>
            <title>Stories by Mahesh Bhanushali on Medium</title>
            <link>https://medium.com/@bhanushalimahesh3?source=rss-215e1cd64ac1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:25:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhanushalimahesh3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a RESTful CRUD API with Node.js, JWT, Bcrypt, Express and MongoDB]]></title>
            <link>https://medium.com/zero-equals-false/building-a-restful-crud-api-with-node-js-jwt-bcrypt-express-and-mongodb-4e1fb20b7f3d?source=rss-215e1cd64ac1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1fb20b7f3d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Mahesh Bhanushali]]></dc:creator>
            <pubDate>Sun, 29 Apr 2018 22:22:01 GMT</pubDate>
            <atom:updated>2020-07-25T16:25:39.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CLep3pLYo0Li5_1FBQ43A.jpeg" /></figure><h3>Introduction</h3><p>In this tutorial we will be developing simple REST API for movies collection with their released date. We gonna implement simple CRUD(Create, Read, Update and Delete) operations on movie collection data in our journey.</p><p>Our application will have public API as well as protected API when we say public that mean it can be accessed without any authentication whereas protected we need to authenticate our self to access them. For authentication, we will be using JWT(Json Web Token). Movie collection application will have the following workflow</p><ul><li>User register through the registration form. (Name, Email, Password)</li><li>The user is authenticated by providing email and password</li><li>On successful authentication, JsonWebToken(JWT) is returned in response to access protected routes.</li><li>In subsequent access to protected route, the user sends JWT token in the header for authentication instead of email and password.</li></ul><h3>Prerequisite</h3><p>Before we start with coding following list needs to be installed. I am working on windows environment.</p><ul><li><a href="https://nodejs.org/en/download/">nodejs</a></li><li><a href="https://www.npmjs.com/get-npm">npm</a></li><li><a href="https://www.mongodb.com/download-center?jmp=nav#community">mongodb</a></li></ul><blockquote>For windows environment MongoDB community version is recommended for quick start</blockquote><p>I assume above list has been installed successfully on your development environment</p><h3>Implementation</h3><p>Open terminal and navigate to directory where you want your application to stay and follow following steps</p><pre>mkdir node-rest-api-jwt<br>cd node-rest-api-jwt<br>npm init</pre><p>After <strong>npm init</strong> you will be asked few questions one by one, keep default options as it is and keep hitting enter button</p><pre>package name: (node-rest-api-jwt)<br>version: (1.0.0)<br>description:<br>entry point: (index.js)<br>test command:<br>git repository:<br>keywords:<br>author:<br>license: (ISC)<br>About to write to C:\NodejsTut\node-rest-api-jwt\package.json:<br>{<br> “name”: “node-rest-api-jwt”,<br> “version”: “1.0.0”,<br> “description”: “”,<br> “main”: “index.js”,<br> “scripts”: {<br> “test”: “echo \”Error: no test specified\” &amp;&amp; exit 1&quot;<br> },<br> “author”: “”,<br> “license”: “ISC”<br>}</pre><pre>Is this OK? (yes)</pre><p>Now install following dependencies</p><pre>npm install bcrypt body-parser express jsonwebtoken mongoose morgan --save</pre><pre>npm install nodemon -g</pre><ul><li><a href="https://www.npmjs.com/package/bcrypt">bcrypt</a> :- hash your plain password and store hashed password in database</li><li>body<a href="https://www.npmjs.com/package/body-parser">-</a>parser :- Parse incoming request bodies in a middleware before your handlers, available under the req.bodyproperty</li><li><a href="https://expressjs.com/">express </a>:- Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.</li><li><a href="https://www.npmjs.com/package/jsonwebtoken">jsonwebtoken </a>:- JSON Web Token (JWT) is an open standard (<a href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.</li></ul><blockquote>You can read more about <a href="https://jwt.io/introduction/">JWT</a></blockquote><ul><li><a href="https://github.com/Automattic/mongoose">mongoose</a> :- Mongoose is a <a href="https://www.mongodb.org/">MongoDB</a> object modeling tool designed to work in an asynchronous environment.</li><li><a href="https://github.com/expressjs/morgan">morgan</a> :- HTTP request logger middleware for node.js</li><li><a href="https://github.com/remy/nodemon">nodemon</a> :- nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application.</li></ul><p>After installing dependencies your package.json file will have the list of all installed dependencies</p><pre>&quot;dependencies&quot;: {<br>    &quot;bcrypt&quot;: &quot;2.0.1&quot;,<br>    &quot;body-parser&quot;: &quot;1.18.2&quot;,<br>    &quot;express&quot;: &quot;4.16.3&quot;,<br>    &quot;jsonwebtoken&quot;: &quot;8.2.1&quot;,<br>    &quot;mongoose&quot;: &quot;5.0.13&quot;,<br>    &quot;morgan&quot;: &quot;1.9.0&quot;<br>  },</pre><p>Now we are good to start with development. Move to root folder of the application i.e node-rest-api-jwt and create following directory</p><pre>cd node-rest-api-jwt<br>mkdir app<br>cd app<br>mkdir api<br>cd api<br>mkdir controllers<br>mkdir models</pre><p>We will follow MVC pattern so our application controllers and models files will be stored in app/api/controllers, app/api/models respective directories.</p><p>create folder config inside application root directory.</p><pre>mkdir config</pre><p>We will store our database configuration file in config folder. i.e node-rest-api-jwt/config</p><p>Next we will create route folder inside our application root directory where all of our application related routes files will be created.</p><pre>mkdir routes</pre><p>Lets create node server, create a file server.js inside directory node-rest-api-jwt</p><pre>const express = require(&#39;express&#39;); <br>const logger = require(&#39;morgan&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const app = express();</pre><pre>app.use(logger(&#39;dev&#39;));<br>app.use(bodyParser.urlencoded({extended: false}));</pre><pre>app.get(&#39;/&#39;, function(req, res){<br> res.json({&quot;tutorial&quot; : &quot;Build REST API with node.js&quot;});<br>});</pre><pre>app.listen(3000, function(){ console.log(&#39;Node server listening on port 3000&#39;);});</pre><p>Now open terminal and from application root folder fire command</p><pre>nodemon server.js</pre><p>You will see in terminal</p><pre>[nodemon] 1.11.0<br>[nodemon] to restart at any time, enter `rs`<br>[nodemon] watching: *.*<br>[nodemon] starting `node server.js`<br>Node server listening on port 3000</pre><p>Now open browser and type localhost:3000/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-bZGEKdDWrim30X5F53kw.png" /><figcaption>http://localhost:300</figcaption></figure><p>Now lets create model file for user in node-rest-api-jwt/app/api/models/users.js</p><pre>const mongoose = require(&#39;mongoose&#39;);<br>const bcrypt = require(&#39;bcrypt&#39;);<br>const saltRounds = 10;</pre><pre>//Define a schema<br>const Schema = mongoose.Schema;</pre><pre>const UserSchema = new Schema({<br> name: {<br>  type: String,<br>  trim: true,  <br>  required: true,<br> },<br> email: {<br>  type: String,<br>  trim: true,<br>  required: true<br> },<br> password: {<br>  type: String,<br>  trim: true,<br>  required: true<br> }<br>});</pre><pre>// hash user password before saving into database<br>UserSchema.pre(&#39;save&#39;, function(next){<br>this.password = bcrypt.hashSync(this.password, saltRounds);<br>next();<br>});</pre><pre>module.exports = mongoose.model(&#39;User&#39;, UserSchema);</pre><p>In model file we include mongoose for model schema, bcrypt to hash our password and also defined salt round which will be used for hashing plain text password. Mongoose provide middleware(pre/post hooks) which we can use to manipulate our data before/after inserting into database. We have used <strong>pre hook save method</strong> to hash our password before saving into database. In <strong>pre hooks</strong> callback function <strong>this</strong> keyword refer to UserSchema object and this.password is password passed from registration form which we will be creating soon. You can read more about mongoose and its function at <a href="https://github.com/Automattic/mongoose">https://github.com/Automattic/mongoose</a></p><p>Now create controller for user in node-rest-api-jwt/app/api/controllers/users.js</p><pre>const userModel = require(&#39;../models/users&#39;);<br>const bcrypt = require(&#39;bcrypt&#39;); <br>const jwt = require(&#39;jsonwebtoken&#39;);</pre><pre>module.exports = {<br> create: function(req, res, next) {<br>  <br>  userModel.create({ name: req.body.name, email: req.body.email, password: req.body.password }, function (err, result) {<br>      if (err) <br>       next(err);<br>      else<br>       res.json({status: &quot;success&quot;, message: &quot;User added successfully!!!&quot;, data: null});<br>      <br>    });<br> },</pre><pre>authenticate: function(req, res, next) {<br>  userModel.findOne({email:req.body.email}, function(err, userInfo){<br>     if (err) {<br>      next(err);<br>     } else {</pre><pre>if(bcrypt.compareSync(req.body.password, userInfo.password)) {</pre><pre>const token = jwt.sign({id: userInfo._id}, req.app.get(&#39;secretKey&#39;), { expiresIn: &#39;1h&#39; });</pre><pre>res.json({status:&quot;success&quot;, message: &quot;user found!!!&quot;, data:{user: userInfo, token:token}});</pre><pre>}else{</pre><pre>res.json({status:&quot;error&quot;, message: &quot;Invalid email/password!!!&quot;, data:null});</pre><pre>}<br>     }<br>    });<br> },</pre><pre>}</pre><p>User controller include user model, jsonwebtoken module and bcrypt. And we have defined two methods</p><ul><li>create :- To create new users, this function has model query too create new user into database.</li><li>authenticate :- In this function we search for user in database by email id and compare plain password passed through login form with database hashed password, if password match we generate jwt token by passing user id and secret key, and have set 1hr validity of the token. You can explore more option on jwt at <a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a> &amp; <a href="https://github.com/auth0/node-jsonwebtoken">https://github.com/auth0/node-jsonwebtoken</a></li></ul><p>Now time to create routes for above users controller methods, node-rest-api-jwt/routes/users.js</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const userController = require(&#39;../app/api/controllers/users&#39;);</pre><pre>router.post(&#39;/register&#39;, userController.create);<br>router.post(&#39;/authenticate&#39;, userController.authenticate);</pre><pre>module.exports = router;</pre><p>In route we included user controller and each post route is mapped with respective controller method.</p><p>Create model, controller and route file for protected movie routes as we created for user</p><p>node-rest-api-jwt/app/api/controllers/movies.js</p><pre>const movieModel = require(&#39;../models/movies&#39;);</pre><pre>module.exports = {<br> getById: function(req, res, next) {<br>  console.log(req.body);<br>  movieModel.findById(req.params.movieId, function(err, movieInfo){<br>   if (err) {<br>    next(err);<br>   } else {<br>    res.json({status:&quot;success&quot;, message: &quot;Movie found!!!&quot;, data:{movies: movieInfo}});<br>   }<br>  });<br> },</pre><pre>getAll: function(req, res, next) {<br>  let moviesList = [];</pre><pre>movieModel.find({}, function(err, movies){<br>   if (err){<br>    next(err);<br>   } else{<br>    for (let movie of movies) {<br>     moviesList.push({id: movie._id, name: movie.name, released_on: movie.released_on});<br>    }<br>    res.json({status:&quot;success&quot;, message: &quot;Movies list found!!!&quot;, data:{movies: moviesList}});<br>       <br>   }</pre><pre>});<br> },</pre><pre>updateById: function(req, res, next) {<br>  movieModel.findByIdAndUpdate(req.params.movieId,{name:req.body.name}, function(err, movieInfo){</pre><pre>if(err)<br>    next(err);<br>   else {<br>    res.json({status:&quot;success&quot;, message: &quot;Movie updated successfully!!!&quot;, data:null});<br>   }<br>  });<br> },</pre><pre>deleteById: function(req, res, next) {<br>  movieModel.findByIdAndRemove(req.params.movieId, function(err, movieInfo){<br>   if(err)<br>    next(err);<br>   else {<br>    res.json({status:&quot;success&quot;, message: &quot;Movie deleted successfully!!!&quot;, data:null});<br>   }<br>  });<br> },</pre><pre>create: function(req, res, next) {<br>  movieModel.create({ name: req.body.name, released_on: req.body.released_on }, function (err, result) {<br>      if (err) <br>       next(err);<br>      else<br>       res.json({status: &quot;success&quot;, message: &quot;Movie added successfully!!!&quot;, data: null});<br>      <br>    });<br> },</pre><pre>}</pre><p>node-rest-api-jwt/app/api/models/movies.js</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>//Define a schema<br>const Schema = mongoose.Schema;</pre><pre>const MovieSchema = new Schema({<br> name: {<br>  type: String,<br>  trim: true,  <br>  required: true,<br> },<br> released_on: {<br>  type: Date,<br>  trim: true,<br>  required: true<br> }<br>});</pre><pre>module.exports = mongoose.model(&#39;Movie&#39;, MovieSchema)</pre><p>node-rest-api-jwt/routes/movies.js</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const movieController = require(&#39;../app/api/controllers/movies&#39;);</pre><pre>router.get(&#39;/&#39;, movieController.getAll);<br>router.post(&#39;/&#39;, movieController.create);<br>router.get(&#39;/:movieId&#39;, movieController.getById);<br>router.put(&#39;/:movieId&#39;, movieController.updateById);<br>router.delete(&#39;/:movieId&#39;, movieController.deleteById);</pre><pre>module.exports = router;</pre><p>Open server.js file and update existing code with following</p><pre>const express = require(&#39;express&#39;);<br>const logger = require(&#39;morgan&#39;);<br>const movies = require(&#39;./routes/movies&#39;) ;<br>const users = require(&#39;./routes/users&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const mongoose = require(&#39;./config/database&#39;); //database configuration<br>var jwt = require(&#39;jsonwebtoken&#39;);<br>const app = express();</pre><pre>app.set(&#39;secretKey&#39;, &#39;nodeRestApi&#39;); // jwt secret token</pre><pre>// connection to mongodb<br>mongoose.connection.on(&#39;error&#39;, console.error.bind(console, &#39;MongoDB connection error:&#39;));</pre><pre>app.use(logger(&#39;dev&#39;));<br>app.use(bodyParser.urlencoded({extended: false}));</pre><pre>app.get(&#39;/&#39;, function(req, res){<br>res.json({&quot;tutorial&quot; : &quot;Build REST API with node.js&quot;});<br>});</pre><pre>// public route<br>app.use(&#39;/users&#39;, users);</pre><pre>// private route<br>app.use(&#39;/movies&#39;, validateUser, movies);</pre><pre>app.get(&#39;/favicon.ico&#39;, function(req, res) {<br>    res.sendStatus(204);<br>});</pre><pre>function validateUser(req, res, next) {<br>  jwt.verify(req.headers[&#39;x-access-token&#39;], req.app.get(&#39;secretKey&#39;), function(err, decoded) {<br>    if (err) {<br>      res.json({status:&quot;error&quot;, message: err.message, data:null});<br>    }else{<br>      // add user id to request<br>      req.body.userId = decoded.id;<br>      next();<br>    }<br>  });<br>  <br>}</pre><pre>// express doesn&#39;t consider not found 404 as an error so we need to handle 404 explicitly<br>// handle 404 error<br>app.use(function(req, res, next) {<br> let err = new Error(&#39;Not Found&#39;);<br>    err.status = 404;<br>    next(err);<br>});</pre><pre>// handle errors<br>app.use(function(err, req, res, next) {<br> console.log(err);<br> <br>  if(err.status === 404)<br>   res.status(404).json({message: &quot;Not found&quot;});<br>  else <br>    res.status(500).json({message: &quot;Something looks wrong :( !!!&quot;});</pre><pre>});</pre><pre>app.listen(3000, function(){<br> console.log(&#39;Node server listening on port 3000&#39;);<br>});</pre><p>To access movie routes we have defined middleware to validate user</p><pre>// private route<br>app.use(&#39;/movies&#39;, validateUser, movies);</pre><pre>function validateUser(req, res, next) {<br>  jwt.verify(req.headers[&#39;x-access-token&#39;], req.app.get(&#39;secretKey&#39;), function(err, decoded) {<br>    if (err) {<br>      res.json({status:&quot;error&quot;, message: err.message, data:null});<br>    }else{<br>      // add user id to request<br>      req.body.userId = decoded.id;<br>      next();<br>    }<br>  });<br>  <br>}</pre><h3>Database Connection</h3><p>Create database connection configuration file in node-rest-api-jwt/config/database.js</p><pre>//Set up mongoose connection<br>const mongoose = require(&#39;mongoose&#39;);<br>const mongoDB = &#39;mongodb://localhost/node_rest_api&#39;;<br>mongoose.connect(mongoDB);<br>mongoose.Promise = global.Promise;</pre><pre>module.exports = mongoose;<br></pre><p>and in server.js file we have setup connection to MongoDB</p><pre>// connection to mongodb<br>mongoose.connection.on(&#39;error&#39;, console.error.bind(console, &#39;MongoDB connection error:&#39;));</pre><p>For windows users to start MongoDB server if you have installed community version on your system</p><p>Create a data folder in node-rest-api-jwt.</p><pre>mkdir data</pre><p>Now open terminal navigate to mongo folder where you have installed mostly it will be in c:\Program Files\MongoDB\Server\3.4|3.2\bin</p><pre>mongod --dbpath c:\path to node-rest-api-jwt\data</pre><p>This command will start MongoDB server and store all your collection in your application data folder, now open another terminal and hit command</p><pre>nodemon server.js<br></pre><blockquote>You can view your MongoDB collection by installing <a href="https://robomongo.org/">Robo 3T</a> application</blockquote><p>One thing I want to add here is that you have noticed we haven’t created any collection in MongoDB, so creating collection on fly is handled by mongoose. You can read more on this by exploring mongoose document.</p><h3>Testing</h3><p>For testing we will user http client postman</p><p>route list</p><ul><li>GET <a href="http://localhost:3000/">http://localhost:3000</a></li><li>POST <a href="http://localhost:3000/users/register">http://localhost:3000/users/register</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzsRCrXf3woIs5hgFk9azQ.png" /><figcaption>POST <a href="http://localhost:3000/users/register">http://localhost:3000/users/register</a></figcaption></figure><ul><li>POST <a href="http://localhost:3000/users/authenticate">http://localhost:3000/users/authenticate</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rS1Gdvs3kdOIbGV3D7YfFg.png" /><figcaption>POST <a href="http://localhost:3000/users/authenticate">http://localhost:3000/users/authenticate</a></figcaption></figure><p>JWT token received in above request will be used to access protected movie routes. We will pass token in header with key=x-access-token and value=jwt token</p><ul><li>POST <a href="http://localhost:3000/movies/">http://localhost:3000/movies</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-SgxkyYJhagTPOT1djt-g.png" /><figcaption>POST <a href="http://localhost:3000/movies/">http://localhost:3000/movies</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQeBrjiYsukLn9rulrSCpQ.png" /><figcaption>POST <a href="http://localhost:3000/movies/">http://localhost:3000/movies</a></figcaption></figure><ul><li>GET <a href="http://localhost:3000/movies">http://localhost:3000/movies</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gz7v02ZpeLir4ZUS-7vPAw.png" /><figcaption><a href="http://localhost:3000/movies">http://localhost:3000/movies</a></figcaption></figure><ul><li>GET <a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgxeahxixd9i6ayDHKb8Ng.png" /><figcaption><a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></figcaption></figure><ul><li>PUT <a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ERlsK-f7Oeci_OhpbZYBA.png" /><figcaption><a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4g8tm1dUyDqKlddGqCMBg.png" /><figcaption><a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></figcaption></figure><ul><li>DELETE <a href="http://localhost:3000/movies/5ae63c5027bbe422cce696a3">http://localhost:3000/movies/5ae63c5027bbe422cce696a3</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twNPoNx3KJGUn92ZMhxRpg.png" /></figure><h3>Conclusion</h3><p>In this tutorial we learned to develop REST API with simple CRUD operation, hashing user plain password using bcrypt and JWT token. If have any queries/suggestion please leave a comment and keep following for more such tuts</p><blockquote>You can find complete code on <a href="https://github.com/bhanushalimahesh3/node-rest-api-jwt">github</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1fb20b7f3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-equals-false/building-a-restful-crud-api-with-node-js-jwt-bcrypt-express-and-mongodb-4e1fb20b7f3d">Building a RESTful CRUD API with Node.js, JWT, Bcrypt, Express and MongoDB</a> was originally published in <a href="https://medium.com/zero-equals-false">Zero Equals False</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a simple website with Node.js, Express and EJS view engine]]></title>
            <link>https://medium.com/@bhanushalimahesh3/creating-a-simple-website-with-node-js-express-and-ejs-view-engine-856382a4578f?source=rss-215e1cd64ac1------2</link>
            <guid isPermaLink="false">https://medium.com/p/856382a4578f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[beginner-javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Mahesh Bhanushali]]></dc:creator>
            <pubDate>Sun, 01 Apr 2018 10:01:37 GMT</pubDate>
            <atom:updated>2018-07-21T12:51:52.108Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial is for beginners who wanted to start with Node.js. We will be creating a simple website with Node.js and the Express framework and will be using EJS view engine to manage our HTML code.</p><p><strong>Prerequisites</strong><br>Step 1: Install nodejs and npm</p><p>Follow links as per your development environment</p><ol><li><a href="https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-16-04">Linux</a></li><li><a href="https://nodejs.org/en/download/">Windows</a></li><li><a href="http://blog.teamtreehouse.com/install-node-js-npm-mac">Mac</a></li></ol><p>If everything installed correctly, open terminal and type node -v and npm -v and you should get the following output based on the version you have installed</p><pre>node -v<br>8.9.1<br>npm -v<br>5.8.0</pre><p>Step 2: Install Express generator package globally (g stand for global in command)</p><pre>npm install express-generator -g</pre><blockquote>Read more about express at <a href="https://expressjs.com/">https://expressjs.com/</a></blockquote><p>Step 3: To run our node server we will install the nodemon package globally</p><pre>npm install nodemon -g</pre><blockquote>Read more about nodemon at <a href="https://www.npmjs.com/package/nodemon">https://www.npmjs.com/package/nodemon</a></blockquote><blockquote><strong>I hope we are on the same page till now, its time to get our hands dirty with some code. Fasten your seatbelt Here we go….</strong></blockquote><p>Open a terminal and move to your directory where you want your code to reside and type</p><pre>express --view=ejs mywebsite</pre><p>As I told we will be using ejs view engine to manage our HTML code throughout our tutorial and this command will create skeleton of our node application and will set ejs as our default view engine</p><p>Next step is to install all dependencies listed in mywebsite/package.json file. Move to your myapp directory and type</p><pre>npm install</pre><p>Now we are all set to run our node server, type command</p><pre>nodemon start</pre><p>If you see following output in your terminal, voila!!! node server is up and running</p><pre>[nodemon] 1.11.0<br>[nodemon] to restart at any time, enter `rs`<br>[nodemon] watching: *.*<br>[nodemon] starting `node ./bin/www start`</pre><p>Now open your browser and tune to the following URL</p><pre><a href="http://localhost:3000/">http://localhost:3000</a></pre><p>You will see the following page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_blsTP6A5EYmjkzSh7N79w.png" /><figcaption>http://localhost:3000</figcaption></figure><blockquote>3000 is port no which is configured by default, you can change by editing mywebsite/bin/www file.</blockquote><p>Open mywebsite/app.js file, you will see</p><pre>var index = require(&#39;./routes/index&#39;);</pre><p>So this is place where we will be defining all our website routes i.e. routes/index file.</p><p>Open your routes/index.js file and replace your route entry.</p><pre>Old <br>/* GET home page. */<br>router.get(&#39;/&#39;, function(req, res, next) {<br>  res.render(&#39;index&#39;, { title: &#39;Express&#39; });<br>});</pre><pre>New <br>/* GET home page. */<br>router.get(&#39;/&#39;, function(req, res, next) {<br>  res.render(&#39;index&#39;, {page:&#39;Home&#39;, menuId:&#39;home&#39;});<br>});</pre><p>we are passing page and menuId variable to index view file.</p><p>Now open your views/index.ejs file and replace your code with following</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br> &lt;% include partials/head %&gt; <br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;% include partials/menu %&gt;</pre><pre>&lt;div class=&quot;container-fluid bg-3 text-center&quot;&gt;    <br>  &lt;h3&gt;&lt;%= page %&gt;&lt;/h3&gt;&lt;br&gt;<br>  &lt;div class=&quot;row&quot;&gt;<br>    &lt;div class=&quot;col-sm-4&quot;&gt;<br>      &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&lt;/p&gt;<br>      <br>    &lt;/div&gt;<br>    &lt;div class=&quot;col-sm-4&quot;&gt; <br>      &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;col-sm-4&quot;&gt; <br>      &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;/body&gt;<br>&lt;% include partials/script %&gt;<br>&lt;/html&gt;</pre><p>Create partials directory in mywebsite/views directory and create following files in partials directory</p><ol><li>head.ejs</li></ol><pre><br>&lt;title&gt;Static Website | &lt;%= page %&gt;&lt;/title&gt;<br>&lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;meta name=&quot;active-menu&quot; content=&quot;&lt;%= menuId %&gt;&quot;&gt;<br>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css</a>&quot;&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;./stylesheets/style.css&quot;&gt;</pre><p>2. menu.ejs</p><pre>&lt;nav class=&quot;navbar navbar-default&quot;&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;navbar-header&quot;&gt;<br>      &lt;button type=&quot;button&quot; class=&quot;navbar-toggle&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#myNavbar&quot;&gt;<br>        &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>        &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;<br>        &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt;                        <br>      &lt;/button&gt;<br>      &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;LOGO&lt;/a&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;myNavbar&quot;&gt;<br>      &lt;ul class=&quot;nav navbar-nav navbar-right&quot;&gt;<br>        &lt;li id=&quot;home&quot;&gt;&lt;a href=&quot;/&quot;&gt;HOME&lt;/a&gt;&lt;/li&gt;<br>        &lt;li id=&quot;about&quot;&gt;&lt;a href=&quot;/about&quot;&gt;ABOUT US&lt;/a&gt;&lt;/li&gt;<br>        &lt;li id=&quot;contact&quot;&gt;&lt;a href=&quot;/contact&quot;&gt;CONTACT US&lt;/a&gt;&lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/nav&gt;</pre><p>3. script.ejs</p><pre>&lt;script src=&quot;<a href="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js</a>&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js</a>&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;./javascripts/menu.js&quot;&gt;&lt;/script&gt;</pre><p>If you have noticed we have seperated our header, topbar menu and master scripts(javascript which need to be load in all pages) code. And all the partials files are included in views/index.ejs file</p><pre>&lt;% include partials/head %&gt; <br> &lt;% include partials/menu %&gt;<br> &lt;% include partials/script %&gt;</pre><p>Create javascripts and stylesheets directory inside mywebsite/public directory and create new file menu.js inside javascript directory and style.css inside stylesheets directory, I have created these 2 files just to show how we can load external CSS and js file in our app.</p><p>4. menu.js</p><pre>$(document).ready(function(){<br>    var element = $(&#39;meta[name=&quot;active-menu&quot;]&#39;).attr(&#39;content&#39;);<br>    $(&#39;#&#39; + element).addClass(&#39;active&#39;);<br>});</pre><p>5. style.css</p><pre>.bg-3 { <br>      background-color: #ffffff;<br>      color: #555555;<br>  }<br>  .container-fluid {<br>      padding-top: 70px;<br>      padding-bottom: 70px;<br>  }<br>  .navbar {<br>      padding-top: 15px;<br>      padding-bottom: 15px;<br>      border: 0;<br>      border-radius: 0;<br>      margin-bottom: 0;<br>      font-size: 12px;<br>      letter-spacing: 5px;<br>  }<br>  .navbar-nav  li a:hover {<br>      color: #1abc9c !important;<br>  }</pre><pre>.active&gt;a {<br>    color: #1abc9c !important;;<br>  }</pre><p>Now again tune to URL <a href="http://localhost:3000/">http://localhost:3000</a>, our updated home page will be loaded similarly, you can create multiple static views like we did for index page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRmXBvBMQXzs6k6jDN10Mw.png" /><figcaption>updated home page with topbar menu</figcaption></figure><blockquote>You can find complete code on <a href="https://github.com/bhanushalimahesh3/node-website">GitHub</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856382a4578f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>