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

in #utopian-io7 years ago (edited)

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

npm install express body-parser mongoose jsonwebtoken cors

  • 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


{
  "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"
  }
}

  • 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


module.exports = {
    'secret'    : 'This secret key',
    'database'  : 'mongodb://127.0.0.1/jwtusers'
}

  • '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= {}


  • 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


//=======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');

  • 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


//=======Local Setup
var config  = require('./app/config');
var user    = require('./app/models/user');
var port    = 3000;

  • 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. so we can request URL like get, post, put, patch or etc.

Setting


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);

  • 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 andsecond 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: node server.js

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

mongod

  • 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
db.users.insert() : 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


//object
{
key: value,
key: value,
...........
}

  • Make models in mongoose

var mongoose =  require('mongoose');
var schema =  mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
    email    : String,
    password: String
}));

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


app.get('/users',function(req,res){
    User.find({},function(err, users){
        res.json(users);
    })
})

  • 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 therequest (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

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...



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thanks for the contribution.


Need help? Write a ticket on https://support.utopian.io.
Chat with us on Discord.

[utopian-moderator]

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!

Vote for Utopian Witness! 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