create account

Consuming JWT API with MongoDB and Node.js part-1# Setup JWT, Setup database, Create Route API by alfarisi94

View this thread on: hive.blogpeakd.comecency.com
· @alfarisi94 · (edited)
$42.29
Consuming JWT API with MongoDB and Node.js part-1# Setup JWT, Setup database, Create Route API
#### What Will I Learn?
- Create and setup server node.js
- Create database, insert database in Mongoose
- Create a route for API Express

#### Requirements

- Install node.js
- Install Express.js
- Install Postman
- Basic node.js, javascript es6
- Basic Mongoose

#### Difficulty

- Intermediate

### Introduction of JWT (JSON Web Token)
**JWT (JSON Web Token)** is one way of the authentication system that uses authentication tokens. if user authentication typically uses sessions, this will incriminate the server. because the session will use space on our server. either by using JWT we will not overload the server.  In Jwt everytime we want to do something we will also send the token we have generated.

### Setup App JWT
We will use JWT (JSON Web Token) on the server side using ***Node.js***. 
Please install **Npm init** in your project folder.  After Npm init you will get package.json in your folder.

- **Install Dependencies**

We need to install some things. They are ***express***, ***mongoose***, ***jsonwebtoken***, and ***cors***. We can install all Dependencies with NPM

<code>npm install express body-parser mongoose jsonwebtoken cors</code>

- express: Miniframework for nodejs.
- mongoose: This for the database.
- jsonwebtoken: This is a package from **JWT**.
- cors: It's useful connecting multiple sites with multiple request method.

After we successfully install the packages. we can see it in ***package.json***
<pre>
<code>
{
  "name": "nodejwt",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "cors": "^2.8.4",
    "express": "^4.16.3",
    "jsonwebtoken": "^8.2.1",
    "mongoose": "^5.0.16"
  }
}
</code>
</pre>

- **Create config.js**

We will make a simple config useful for storing our server configuration.  We can create a file with the name **config.js**
<pre>
<code>
module.exports = {
	'secret'	: 'This secret key',
	'database'	: 'mongodb://127.0.0.1/jwtusers'
}
</code>
</pre>

- 'secret':  We can provide the credentials of the secret key. the contents of the secret key are up to your will.
- 'database': We can run the database on localhost by using MongoDB: //127.0.0.1/jwtusers. **/jwtusers** is the name of the database, and **127.0.0.1** is the port of database.
then we export by using ***module.export=  {}***
<br>

<br>
- **Create server**

We can create a file that we will use as a server. in this tutorial, I named **server.js**.  We need to set up on our file server. We will do two type setup, the first is set up for global server and the second is set up local part such as database and others.

**Setup**
<pre>
<code>
//=======Set up
var express = require('express');
var bodyParser = require('body-parses');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var app = express();
var router = express.Router();
var cors = require('cors');
</code>
</pre>

- require('express'), require('body-parses'), require('mongoose'), require('jsonwebtoken') : To initialize the package we will use, and save it in the variable.
- var app = express(): To initialize Miniframework Express.
- var router = express.Router(): To initialize Router Express.

**Local Setup**
<pre>
<code>
//=======Local Setup
var config 	= require('./app/config');
var user 	= require('./app/models/user');
var port 	= 3000;
</code>
</pre>

- var config 	= require('./app/config'): We loaded the config file we created earlier. We can setour file directory. in this tutorial my file directory is on **'./app/config'**.
- var user 	= require('./app/models/user'): We loaded the user models file we created earlier. 
we can set our file directory. in this tutorial my file directory is on **'./app/models/user'**.
- var port 	= 3000:  We can define its port at **3000**.

To hit endpoints or to access the page I will use [postman](https://www.getpostman.com). so we can request URL like ***get, post, put, patch or etc***.

**Setting**
<pre>
<code>
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
mongoose.connect(config.database);
app.set('secretKey', config.secret);
app.use(cors());
app.listen(port);
</code>
</pre>

- bodyParser.urlencoded:  bodyParser is an initialization from var **bodyParser**= require('body-parses');, We need a body-parser so that the API that we created can read the data sent by the user either through the form or in the form of JSON.
- mongoose.connect(config.database): We can connect to the mongoose database with the ***connect()*** function, and pass parameters that contain the configuration of our database we have created in **config.js**.
- app.set('secretKey', config.secret): We can set the key by way of the ***set()*** function. ***set ()*** has two parameters which **first is key** and**second is value**. in this tutorial my key is **'secretKey'** and its value comes from the **config.js** file , that is **config.secret**.
- app.use(cors()):  We can use the cors we have installed with ***use(cors())***, It's usefull connecting multiple site with multiple request method.
and finally we can run the server with **app.listen(port)**. **port **parameter is **var port = 3000**.
You can run the server.js in command prompt: <code>node server.js</code>

### Set up a database with mongoose
We have made a mongoose connection with **mongoose.connect () on server.js**. 
but we have not filled the database yet. We can open the command prompt or terminal in our project and run mongod.

- **run database server**

<code>mongod</code>

- **choose database**

We can choose the database that we will use, in config.js 'database': 'mongodb://127.0.0.1/**jwtusers**' we have determined will use the database jwtuser.
- **insert data**

We can enter data into our mongoose database in this way
<code>db.users.insert()</code> : **users** is the name of the **jwtusers** database collection. 
and we can user method **insert ()**. and in **insert ()** we can enter data in the form of object
<pre>
<code>
//object
{
key: value,
key: value,
...........
}
</code>
</pre>

- **Make models in mongoose**
<pre>
<code>
var mongoose =  require('mongoose');
var schema =  mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
	email	 : String,
	password: String
}));
</code>
</pre>

We need package mongoose, we can use **require ('mongoose')**,  Any configuration using Mongoose should be accompanied by **Schema**. The schema is a mapping of the MongoDB collection and the definition of the type of data used in each object in the collection. we can use **mongoose.Schema**.  While the model **('User')** is a compiled constructor derived from Schema that we have defined. 

### Create Router
<pre>
<code>
app.get('/users',function(req,res){
	User.find({},function(err, users){
		res.json(users);
	})
})
</code>
</pre>

- We can make the routing by **app.get ('/ nameofRoute', function(req, res))**,  
the first parameter is the name of the routing and the second parameter is a function that we use to receive the**request (req) and response (res)**.
- We can be able to retrieve all the data residing on a model in this way **NameOfModel.find()**.
in this tutorial, the model name is **User**. In the **find()** method there are two parameters. **the first parameter** to retrieve the specific data, and **the second parameter** is a **function** that has two parameters too **function(err, data)**. The first parameter in the form of error **(err)** and the second form of data successfully retrieved **(data)**
- We can change the data into JSON in this way **res.json(The data);**

### Conclusion
We have created a setup and installation of mongoose, express, and others. we have also learned to enter data. now to see the result you can open your postman and open the **localhost: 3000/users**. 
we can see the results of what we input in the mongoose database.

![Screenshot_4.png](https://cdn.utopian.io/posts/0512ae97506c9fa6fbf941bf80f009452533Screenshot_4.png)


We can see the data you input can be accessed via **localhost: 3000 / users**. in the next tutorial, I will make an authentication with JWT and JWT token Verification. Thank you...

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@alfarisi94/consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 121 others
properties (23)
authoralfarisi94
permlinkconsuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":27193779,"name":"node","full_name":"nodejs/node","html_url":"https://github.com/nodejs/node","fork":false,"owner":{"login":"nodejs"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","nodejs","backend","javascript","mongodb"],"users":["alfarisi94"],"links":["https://www.getpostman.com","https://cdn.utopian.io/posts/0512ae97506c9fa6fbf941bf80f009452533Screenshot_4.png"],"image":["https://cdn.utopian.io/posts/0512ae97506c9fa6fbf941bf80f009452533Screenshot_4.png"],"moderator":{"account":"deathwing","time":"2018-04-25T22:10:13.767Z","pending":false,"reviewed":true,"flagged":false},"questions":{"voters":["deathwing"],"answers":[{"question_id":"tuts-1","answer_id":"tuts-1-a-3","user":"deathwing","influence":100},{"question_id":"tuts-2","answer_id":"tuts-2-a-2","user":"deathwing","influence":100},{"question_id":"tuts-3","answer_id":"tuts-3-a-4","user":"deathwing","influence":100},{"question_id":"tuts-4","answer_id":"tuts-4-a-2","user":"deathwing","influence":100},{"question_id":"tuts-5","answer_id":"tuts-5-a-4","user":"deathwing","influence":100},{"question_id":"tuts-6","answer_id":"tuts-6-a-4","user":"deathwing","influence":100},{"question_id":"c-1","answer_id":"c-1-a-2","user":"deathwing","influence":100},{"question_id":"c-2","answer_id":"c-2-a-4","user":"deathwing","influence":100}],"total_influence":0,"most_rated":[{"question_id":"tuts-1","answer_id":"tuts-1-a-3","influence":100,"voters":["deathwing"]},{"question_id":"tuts-2","answer_id":"tuts-2-a-2","influence":100,"voters":["deathwing"]},{"question_id":"tuts-3","answer_id":"tuts-3-a-4","influence":100,"voters":["deathwing"]},{"question_id":"tuts-4","answer_id":"tuts-4-a-2","influence":100,"voters":["deathwing"]},{"question_id":"tuts-5","answer_id":"tuts-5-a-4","influence":100,"voters":["deathwing"]},{"question_id":"tuts-6","answer_id":"tuts-6-a-4","influence":100,"voters":["deathwing"]},{"question_id":"c-1","answer_id":"c-1-a-2","influence":100,"voters":["deathwing"]},{"question_id":"c-2","answer_id":"c-2-a-4","influence":100,"voters":["deathwing"]}]},"score":28.5,"total_influence":100,"staff_pick":null,"config":{"questions":[{"question":"How many substantial concepts does this tutorial address?","question_id":"tuts-1","answers":[{"answer":"4-5 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-1","value":10},{"answer":"2-3 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-2","value":7},{"answer":"1 substantial concept covered in the tutorial.","answer_id":"tuts-1-a-3","value":3},{"answer":"More than 5 substantial concepts covered in the tutorial.","answer_id":"tuts-1-a-4","value":0}]},{"question":"Does the title and the outline of the tutorial properly reflect the content?","question_id":"tuts-2","answers":[{"answer":"Yes, it is very clear.","answer_id":"tuts-2-a-1","value":15},{"answer":"To some extent.","answer_id":"tuts-2-a-2","value":11.5},{"answer":"The title is somewhat misleading and/or the outline is not detailed or informative enough.","answer_id":"tuts-2-a-3","value":4.5},{"answer":"Title and outline are of little or no relevance to the content of the tutorial.","answer_id":"tuts-2-a-4","value":0}]},{"question":"Did the contributor provide supplementary resources, such as code and sample files in the contribution post or a linked GitHub repository?","question_id":"tuts-3","answers":[{"answer":"Yes, exceptional supplementary resources are provided including a relevant github repo/gist.","answer_id":"tuts-3-a-1","value":15},{"answer":"Supplementary resources provided are of high relevance.","answer_id":"tuts-3-a-2","value":12},{"answer":"Contributor provides minimal supplementary resources.","answer_id":"tuts-3-a-3","value":6},{"answer":"No supplementary resources were provided.","answer_id":"tuts-3-a-4","value":0}]},{"question":"Is the tutorial part of a series?","question_id":"tuts-4","answers":[{"answer":"Yes.","answer_id":"tuts-4-a-1","value":10},{"answer":"Yes, but it is the first entry in the series.","answer_id":"tuts-4-a-2","value":7},{"answer":"No, but it works just fine as a stand-alone tutorial.","answer_id":"tuts-4-a-3","value":5},{"answer":"No.","answer_id":"tuts-4-a-4","value":0}]},{"question":"Does the tutorial contain sufficient explanatory visuals?","question_id":"tuts-5","answers":[{"answer":"Yes, the visual components of the post were adequate in quality and quantity.","answer_id":"tuts-5-a-1","value":10},{"answer":"The volume of visual components included was unnecessarily large.","answer_id":"tuts-5-a-2","value":7},{"answer":"The post lacked sufficient visualization to easily learn from the content.","answer_id":"tuts-5-a-3","value":3},{"answer":"No visualization was presented in this contribution.","answer_id":"tuts-5-a-4","value":0}]},{"question":"How unique and/or innovative are the concepts covered in the tutorial?","question_id":"tuts-6","answers":[{"answer":"This was the first time I read about the concepts covered.","answer_id":"tuts-6-a-1","value":10},{"answer":"The concepts covered were innovative and offer some usefulness.","answer_id":"tuts-6-a-2","value":7},{"answer":"I have read several similar ideas and thoughts elsewhere, but this one was of higher quality.","answer_id":"tuts-6-a-3","value":5},{"answer":"Such tutorials can be found online with great ease and the contribution add no value to the open source community.","answer_id":"tuts-6-a-4","value":0}]},{"question":"How would you describe the formatting, language and overall presentation of the post?","question_id":"c-1","answers":[{"answer":"The quality of the post is fantastic.","answer_id":"c-1-a-1","value":10},{"answer":"The post is of very good quality.","answer_id":"c-1-a-2","value":7},{"answer":"The post is poorly written and/or formatted, but readable.","answer_id":"c-1-a-3","value":3},{"answer":"The post is really hard to read and the content is barely understandable.","answer_id":"c-1-a-4","value":0}]},{"question":"How would you rate the overall value of this contribution on the open source community and ecosystem?","question_id":"c-2","answers":[{"answer":"This contribution brings great and impactful value, and can be used for applications outside the specific project.","answer_id":"c-2-a-1","value":20},{"answer":"This contribution adds significant value to the open source community and ecosystem, or is of critical importance to the specific project.","answer_id":"c-2-a-2","value":18},{"answer":"This contribution adds some value to the open source community and ecosystem or is only valuable to the specific project.","answer_id":"c-2-a-3","value":11},{"answer":"This contribution adds no value to the open source community and ecosystem or the specific project.","answer_id":"c-2-a-4","value":0}]}]}}"
created2018-04-25 17:01:36
last_update2018-04-26 00:30:24
depth0
children2
last_payout2018-05-02 17:01:36
cashout_time1969-12-31 23:59:59
total_payout_value30.687 HBD
curator_payout_value11.601 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,498
author_reputation5,678,893,550,406
root_title"Consuming JWT API with MongoDB and Node.js part-1# Setup JWT, Setup database, Create Route API"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id52,100,952
net_rshares7,462,039,874,335
author_curate_reward""
vote details (185)
@deathwing ·
Thanks for the contribution.

----------------------------------------------------------------------
Need help? Write a ticket on https://support.utopian.io.
Chat with us on [Discord](https://discord.gg/uTyJkNm).

**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authordeathwing
permlinkre-alfarisi94-consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api-20180425t221112296z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-04-25 22:11:09
last_update2018-04-25 22:11:09
depth1
children0
last_payout2018-05-02 22:11:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length270
author_reputation269,077,595,754,009
root_title"Consuming JWT API with MongoDB and Node.js part-1# Setup JWT, Setup database, Create Route API"
beneficiaries
0.
accountutopian.pay
weight1,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id52,141,621
net_rshares0
@utopian-io ·
### Hey @alfarisi94! Thank you for the great work you've done!
We're already looking forward to your next contribution!
#### Fully Decentralized Rewards
We hope you will take the time to share your expertise and knowledge by rating contributions made by others on Utopian.io to help us reward the best contributions together.
#### Utopian Witness!
<a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for Utopian Witness!</a> We are made of developers, system administrators, entrepreneurs, artists, content creators, thinkers. We embrace every nationality, mindset and belief.

**Want to chat? Join us on Discord https://discord.me/utopian-io**
properties (22)
authorutopian-io
permlinkre-alfarisi94-consuming-jwt-api-with-mongodb-and-node-js-part-1-setup-jwt-setup-database-create-router-api-20180427t210412459z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-04-27 21:04:12
last_update2018-04-27 21:04:12
depth1
children0
last_payout2018-05-04 21:04:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length690
author_reputation152,955,367,999,756
root_title"Consuming JWT API with MongoDB and Node.js part-1# Setup JWT, Setup database, Create Route API"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id52,522,725
net_rshares0