Wednesday 13 February 2019

AngularJS , ExpressJS and MongoDB connectivity


Creating a Node Application with MongoDB Connectivity


mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init


Installing Express


npm install express --save


Create app.js file
var express = require("express");
var app = express();
var port = 3000;

app.get("/", (req, res) => {
 res.send("Hello World");
});

app.listen(port, () => {
 console.log("Server listening on port " + port);
});

To test our application you can go to the terminal and enter the command
node app.js

Open up a browser and navigate to the url
http://localhost:3000

https://cdn-images-1.medium.com/max/800/1*LR6Q3wQmwKpbUl_sKN6skw.png

Creating Website to Save Data to MongoDB Database


Create index.html
<!DOCTYPE html>

<html>

 <head>

 <title>Intro to Node and MongoDB</title>

 </head>

 

 <body>

 <h1>Into to Node and MongoDB</h1>

 <form method="post" action="/addname">

 <label>Enter Your Name</label><br>

 <input type="text" name="firstName" placeholder="Enter first name..." required>

 <input type="text" name="lastName" placeholder="Enter last name..." required>

 <input type="submit" value="Add Name">

 </form>

 </body>

</html>

The app.get lines will need to be changed

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
});
Once you have saved your app.js file, we can test it by going to terminal and running node app.js
Open your browser and navigate to “http://localhost:3000”. You will see the following

https://cdn-images-1.medium.com/max/800/1*mko0-ItjsVqqjNXVkdPhHg.png



Connecting to the Database


To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose –save

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.
In our app.js file after the line for the port and before the app.get line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var User = mongoose.model("User", nameSchema);

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
});
Creating a Database Schema

var nameSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

var User = mongoose.model("User", nameSchema);

Creating a RESTful API


We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.
An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTML Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.
HTTP Verb         Operation
GET              Read
POST             Create
PUT              Update
DELETE           Delete

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.
In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.
app.post("/addname", (req, res) => {

 

});

Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.
Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.
npm install body-parser --save
To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.
var bodyParser = require('body-parser');

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.
To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.
app.post("/addname", (req, res) => {

 var myData = new User(req.body);

 myData.save()

 .then(item => {

 res.send("item saved to database");

 })

 .catch(err => {

 res.status(400).send("unable to save to database");

 });

});

Testing our code


Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

3 comments:

  1. var express = require("express");
    var app = express();
    var port = 3000;
    var bodyParser = require('body-parser');
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    var mongoose = require("mongoose");
    mongoose.Promise = global.Promise;
    mongoose.connect("mongodb://localhost:27017/node-demo");
    var nameSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
    });
    var User = mongoose.model("User", nameSchema);

    app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
    });

    app.post("/addname", (req, res) => {
    var myData = new User(req.body);
    myData.save()
    .then(item => {
    res.send("Name saved to database");
    })
    .catch(err => {
    res.status(400).send("Unable to save to database");
    });
    });

    app.listen(port, () => {
    console.log("Server listening on port " + port);
    });

    ReplyDelete
  2. This was an authentic and useful piece of information. Thank you for giving this useful content.
    Ethical Hacking Techniques
    What Is a Hacker

    ReplyDelete