Node.js – AppDividend https://appdividend.com Latest Code Tutorials Thu, 14 Feb 2019 00:26:13 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Node.js – AppDividend https://appdividend.com 32 32 Node Express Image Upload and Resize Tutorial Example https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/ https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/#comments Thu, 14 Feb 2019 00:19:04 +0000 http://localhost/wordpress/?p=4827 Node Image Upload Resize Tutorial With Example

Node Express Image Upload and Resize Tutorial Example is today’s topic. Node.js as a platform and express as a lightweight framework is the best choice for backend development. We can build Web APIs through this framework very quickly, and it has tremendous support for the NoSQL databases like MongoDB. You can find the tutorial about Node Express […]

The post Node Express Image Upload and Resize Tutorial Example appeared first on AppDividend.

]]>
Node Image Upload Resize Tutorial With Example

Node Express Image Upload and Resize Tutorial Example is today’s topic. Node.js as a platform and express as a lightweight framework is the best choice for backend development. We can build Web APIs through this framework very quickly, and it has tremendous support for the NoSQL databases like MongoDB. You can find the tutorial about Node Express MongoDB tutorial on this blog. In this tutorial, we will upload an image to the Node.js server and resize the image using the sharp library.

Node Express Image Upload and Resize Tutorial

Okay, now let’s start our project.

Step 1: Create Node Express Project

Create a project folder by the following command.

mkdir nodeimageupload
cd nodeimageupload

Now, create a package.json file using the following command.

npm init -y

Next, install express as a framework,ejs as a template engine, body-parser, multer as a  node.js middleware for handling multipart/form-data, uuid for getting the random name, sharp as an image resize libraries using NPM.

npm install express body-parser ejs uuid multer sharp --save

Also, install the nodemon server as a development dependency.

npm install nodemon --save-dev

Now, open the project in Visual Studio Code.

Change the package.json file and add the following line in “scripts” object.

"scripts": {
    "start": "nodemon server.js"
},

Step 2: Create a server.js file.

Create one file in the project root called the server.js and added the following code inside it.

// server.js

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.listen(port, function () {
  console.log('Server is running on PORT',port);
});

Now, go to the terminal and start the node server by the following command.

npm start

 

Node Express Image Upload and Resize Tutorial Example

So, our nodemon development server is up and running.

Step 3: Configure the EJS templating engine.

For including the css and js files in the express, first, we will create a static directory called public in the root, and in that, we will put our CSS and JS files. So, create the first public directory.

Add the following code inside the server.js file.

// server.js

app.use(express.static('public'));

Next step is to set the ejs template engine. Add the following code inside the server.js file.

// server.js

app.set('view engine', 'ejs');

We need to create one folder inside our root called views. In that folder make one file called index.ejs.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
  </head>
  <body>
    <p>Node Express Image Upload and Resize Example</p>
  </body>
</html>

Also, create an index.html file inside the public folder.

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=He, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node Express Image Upload Example</title>
</head>
<body>
   <p>
     Node Express Image Upload and Resize Example
   </p>
</body>
</html>

Step 4: Configure Express Router.

Set up the routes for our application. So use Router module provided by Express js. So, create a file in the root folder called router.js.

Now, write the following code inside the router.js file.

// router.js

const express = require('express');
const app = express();
const router = express.Router();

router.get('/', async function (req, res) {
  await res.render('index');
});
module.exports = router;

Now in the server.js filewe need to require the router.js file.

// server.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;
const router = require('./router');

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

app.use(express.static('public'));
app.set('view engine', 'ejs');

app.use('/upload', router);

app.listen(port, function () {
  console.log('Server is running on PORT',port);
});

Now, go to the browser and hit this URL: http://localhost:3000/upload. You can see the basic HTML view.

Step 5: Create a form.

Inside the index.ejs file, we need to create one HTML form that can upload the image.

// index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
  </head>
  <body>
      <p>Image Upload</p>
      <form method="post" action="upload/post" enctype="multipart/form-data">
        <input type="file" name="image" /><br /><br />
        <button type="submit" name="upload">Upload</button>
      </form>
  </body>
</html>

Now, go to the http://localhost:3000/upload and see the underlying HTML form that can upload an image.

Step 6: Create file upload middleware

Okay, to handle the multipart/form-data in Node.js, we have already installed the multer library. So let’s use that and create a middleware inside the root of the project called uploadMiddleware.js.

// uploadMiddleware.js

const multer = require('multer');

const upload = multer({
  limits: {
    fileSize: 4 * 1024 * 1024,
  }
});

module.exports = upload

Now, import this middleware inside the router.js file where we handle the POST request.

// router.js

const express = require('express');
const app = express();
const router = express.Router();
const upload = require('./uploadMiddleware');

router.get('/', async function (req, res) {
  await res.render('index');
});

router.post('/post', upload.single('image'), async function (req, res) {
  await console.log('post');
});

module.exports = router;

Here, we have used the node async await feature. 

So, when the user tries to upload an image, in the server, the router. Post function will be executed, and in the console, a post will be printed. That means, now we need to resize the image and then save in the file directory.

Step 7: Resize the image

For resizing the image in Node.js and achieve the High-performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images is Sharp. We have already installed the sharp. Now, create a file inside the root called Resize.js and add the following code.

// Resize.js

const sharp = require('sharp');
const uuidv4 = require('uuid/v4');
const path = require('path');

class Resize {
  constructor(folder) {
    this.folder = folder;
  }
  async save(buffer) {
    const filename = Resize.filename();
    const filepath = this.filepath(filename);

    await sharp(buffer)
      .resize(300, 300, {
        fit: sharp.fit.inside,
        withoutEnlargement: true
      })
      .toFile(filepath);
    
    return filename;
  }
  static filename() {
    return `${uuidv4()}.png`;
  }
  filepath(filename) {
    return path.resolve(`${this.folder}/${filename}`)
  }
}
module.exports = Resize;

So, in the above file, we have created a class called Resize.js and accepts one argument which is folder path up to images folder. Now, you need to create the images folder inside the public directory.

Then, we have defined the static function filename which returns the random string of filename and then define the filepath function which returns the complete filepath of that uploaded image.

Then we have defined the save() function, which accepts the file buffer coming from the user request and then resize that image and upload to that filepath and return the filename to the User.

Now, import the Resize.js file inside the router.js file.

Step 8: Save the image in the file system

Now, we need to import the Resize.js file inside the router.js file because we are handling the post request there. Write the following code inside the router.js file.

// router.js

const express = require('express');
const app = express();
const path = require('path');

const router = express.Router();
const upload = require('./uploadMiddleware');
const Resize = require('./Resize');

router.get('/', async function (req, res) {
  await res.render('index');
});

router.post('/post', upload.single('image'), async function (req, res) {
  const imagePath = path.join(__dirname, '/public/images');
  const fileUpload = new Resize(imagePath);
  if (!req.file) {
    res.status(401).json({error: 'Please provide an image'});
  }
  const filename = await fileUpload.save(req.file.buffer);
  return res.status(200).json({ name: filename });
});

module.exports = router;

First, inside the router.post request, we have defined the upload folder and then pass that folder to the constructor of Resize class. It will return the object and then we call the save() method on that object and pass the image buffer as an argument to the save() function and return the file name and we are for now just displaying the filename in JSON format to the User.

If the file is not there then we are displaying an error message to the user in JSON format.

Step 9: Run the Project.

Now, if you try to upload an image, you will see the output in the browser like below image.

 

Upload and Resize the image

So, we have got the correct JSON response. Now, go to the file system and inside the public >> images folder, you can see the randomly named image will be there.

Finally, Node Express Image Upload and Resize Tutorial Example is over. Thanks for taking and also, see the Github code, if you find any error.

Github Code

The post Node Express Image Upload and Resize Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/feed/ 2
AWS Lambda And Node.js Tutorial | Getting Started With Serverless https://appdividend.com/2019/01/12/aws-lambda-and-node-js-tutorial-getting-started-with-serverless/ https://appdividend.com/2019/01/12/aws-lambda-and-node-js-tutorial-getting-started-with-serverless/#comments Sat, 12 Jan 2019 19:57:55 +0000 http://localhost/wordpress/?p=3397 AWS Lambda Tutorial With Example

In this tutorial, we will see AWS Lambda And Node.js Tutorial | Getting Started With Serverless. In this post, we will see how we can configure the serverless on mac and up and running with aws lambda with nodejs from scratch. We will look at how we can deploy a simple test aws-nodejs application. But before […]

The post AWS Lambda And Node.js Tutorial | Getting Started With Serverless appeared first on AppDividend.

]]>
AWS Lambda Tutorial With Example

In this tutorial, we will see AWS Lambda And Node.js Tutorial | Getting Started With Serverless. In this post, we will see how we can configure the serverless on mac and up and running with aws lambda with nodejs from scratch. We will look at how we can deploy a simple test aws-nodejs application. But before the start, we need to understand some terminology. So let us know that first.

Function As A Service (FAAS)

The architecture AWS Lambda is called either a Serverless Computing or Function as a Service. It’s groundbreaking technology because of the lack of servers.

But wait, that sounds strange. Well the code is not running on potatoes, is it!? Okay, that’s just a saying.

What’s going on here is that you, as a developer, don’t need to worry about the infrastructure your code is running on.

You deploy the code into the cloud, and it handles the creation of all needed resources by itself using the containers.

Every time an AWS Lambda Function is created, a container is spun up to serve it. It’s not a Docker container though, instead of a proprietary container built by AWS.

Principles of FaaS

  1. It completely abstracts the servers away from a developer.
  2. The billing is based on the consumption and executions of functions, not server instance sizes like Amazon EC2.
  3. Services that are event-driven and instantaneously scalable.

On a basic level, you can describe them as a way to run some code when ‘something’ happens, or event occurs like receive an HTTP request from the client.

Well known FaaS Providers

AWS, Azure, and Google Cloud all provide this kind of serverless solution.  A lot of innovation and R&D is still going on in this area, and things are rapidly improving and changing over time. Leading three in the industries are following.

  1. AWS Lambda
  2. Azure Functions
  3. Cloud Functions

Serverless Framework

Serverless is useful to build web, mobile and IoT applications using AWS Lambda and API Gateway, Azure Functions, Google Cloud Functions, and more.

Serverless computing is a cloud-computing execution model in which a cloud provider acts as a server, dynamically managing the allocation of machine resources. 

The pricing is entirely based on the actual amount of resources consumed by an application, rather than on pre-purchased units of capacity used in traditional servers.

Serverless is the native architecture of a cloud that enables you to shift more of your operational responsibilities to AWS, increasing your ability towards your main application logic and less infrastructure centric.

Serverless allows you to build and run applications and services without thinking about servers. 

It eliminates infrastructure management tasks such as server or cluster provisioning, patching, operating system maintenance, and capacity provisioning.

You can build on serverless for nearly any type of application or backend service, and everything required to run and scale your application with high availability is handled for you.

AWS Lambda And Node.js Tutorial

For this task, you need to create an AWS account. It provides a Free-tier with the limitations. You can create your free account here.

You will have a node.js install on your local machine. I am using MacBook Air, and my node version is 11.3.0.

You also need to have an editor. I am using Visual Studio Code.

Step 1: Install Serverless Globally

The first step is to install serverless globally in your local machine. Type the following command to install. If you are using Windows, then open the CMD on administrator mode.

sudo npm install serverless -g

 

AWS Lambda And Node.js Tutorial | Getting Started With Serverless

Ignore that yellow warning; we have successfully installed the serverless in our machine.

Okay, now create a folder called node-lambda and go inside that folder and create an aws-nodejs template.

Now, we can use this serverless package to install a template specific to aws-nodejs. So, let us install aws-nodejs template for serverless.

serverless create -t aws-nodejs

 

Aws Lambda Node.js Installation Template

Open the project on VSCode, and you will see the folder structure like this image.

 

AWS Node js Lambda Folder Structure

Step 2: Create Access Key and Secret For AWS

Next step is to create an access key and secret to connect the serverless with our aws account.

After your successful signup on AWS, you can create your access key and secret.

See the below image, when you logged in, you can click on your name on the upper right corner, and you can see it opens up a drop down and then click on the My Security Credentials.

You will see this kind of page with a popup.

 

Create Access Key and Secret For AWS

For this demo, let’s go with the Continue to security Credentials. However, you can go with the IAM Users policy to create and give access to specific users and policies.

Next, go for Access keys (access key ID and secret access key) and create new keys. You can find both access key and access secret.

Now, you need to provide that keys to the serverless to connect serverless and aws-nodejs.

For that, you need to type the following command in your terminal and in between that command, you need to provide your access key and secret. If you have already done it, then you do not need to do that. Otherwise, you need to do that.

serverless config credentials --provider aws --key your aws key --secret your aws secret

In the above command, you need to place your access key instead of your aws key and place your access secret instead of your aws secret.

After hitting the enter, if your credentials are right, then you will see a success message like below.

 

Setup AWS Serverless Setup

Bingo, you got it right, and now your configuration step is over.

Step 3: Creating your First Function

Now, open the editor in which your project is open and go to the handler.js file.

Modify that code with the following code.

// handler.js

'use strict';

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Expecto Petronum',
      input: event,
    }),
  };
};

So, when the HTTP request hit the AWS Lambda Service URL, we will get a response like this message which is Expecto Petronum.

Now, go to this file called serverless.yml.

I have modified that file with the following code and removed the commented part in the file.

service: lambda-test

provider:
  name: aws
  runtime: nodejs8.10

functions:
  hello:
    handler: handler.hello
    events:
     - http:
         path: users/create
         method: get

What I have done is first, I have changed the service name to lambda-test and added a function called hello, which is inside the handler.js file.

So, when the request hit the URL, this function will execute and gives the response defined in that function.

Okay, now all the coding is done.

We need to deploy this function into the AWS. So type the following command.

serverless deploy

 

Serverless deploy

If the deployment is the first time, then you will see something like this.

 

Serverless AWS Lambda Deploy

So, the endpoint is generated for our service. We can use that endpoint as an API or web service to get a JSON response. So it also becomes a BaaS(Backend as a Service).

Here, in the console, I can see my endpoint to which I can get the response. You also have your endpoint which you can access from your browser. So go to the browser and hit that endpoint and you will see an output like this.

 

serverless aws nodejs tutorial

That is it guys, we have successfully deployed our first function as a service using AWS Lambda.

Step 4: Create a second function

Go to the project inside the VSCode and open the serverless.yml file and add another function called app.

service: lambda-test

provider:
  name: aws
  runtime: nodejs8.10

functions:
  hello:
    handler: handler.hello
    events:
     - http:
         path: users/create
         method: get
  app:
    handler: handler.app
    events:
     - http:
         path: app/get
         method: get

Also, we need to write the code inside the handler.js file. 

This app function decides what to give the response when the URL hit in the browser or API endpoint gets accessed. Let us add a new function inside the handler.js file.

// handler.js

'use strict';

module.exports.hello = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Expecto Petronum',
      input: event,
    }),
  };
};

module.exports.app = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'AppDividend API is accessed',
      input: event,
    }),
  };
};

Save the file and deploy the code.

serverless deploy

 

Create a second function

See in the endpoints section: you have now two endpoints.

So, it is beneficial and easy to create a new function as a backend service, and you will be charged based on how many times your service has been accessed.

If you want to build an API and do not manage any server, then you have this best way to use AWS Lambda to avoid managing your server and focus on only the code. Rest will handle by the cloud service provider.

Finally, AWS Lambda And Node.js Tutorial | Getting Started With Serverless post is over. Thanks for taking.

The post AWS Lambda And Node.js Tutorial | Getting Started With Serverless appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/12/aws-lambda-and-node-js-tutorial-getting-started-with-serverless/feed/ 3
How To Create Blockchain In JavaScript https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/ https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/#comments Sat, 15 Dec 2018 00:58:09 +0000 http://localhost/wordpress/?p=2554 Javascript Blockchain Tutorial With Example From Scratch

In this tutorial, we will see How To Create Blockchain In JavaScript. Blockchain keeps the record of all data exchanges — this record is referred to as the “ledger” in the cryptocurrency world, and each data exchange is the “transaction.“ Every verified transaction is added to the ledger as a “block.” It utilizes the distributed system to verify each […]

The post How To Create Blockchain In JavaScript appeared first on AppDividend.

]]>
Javascript Blockchain Tutorial With Example From Scratch

In this tutorial, we will see How To Create Blockchain In JavaScript. Blockchain keeps the record of all data exchanges — this record is referred to as the “ledger” in the cryptocurrency world, and each data exchange is the “transaction.“ Every verified transaction is added to the ledger as a “block.” It utilizes the distributed system to verify each transaction — the peer-to-peer network of nodes. Once signed and verified, a new transaction is added to the blockchain and cannot be altered.

The blockchain is a structure of data that represents the financial ledger entry, or a record of a transaction. Each transaction is digitally signed to ensure its authenticity and that no one tampers with it, so a ledger itself and the existing transactions within it are assumed to be of high integrity.

In this tutorial, we will create the simple blockchain in javascript in which we use Javascript as a language and Node.js as a backend to run the small project.

How To Create Blockchain In JavaScript

Now if we need to create a simple Blockchain in Node.js, then we need to have one Genesis Block

You can refer to Genesis Block as the first block of Blockchain because Blockchain is an array of blocks and Genesis is the first block of the Blockchain.

Genesis Block

The genesis block is the first block of the blockchain. The genesis block is generally hardcoded in the applications that utilize its blockchain. The Genesis Block is also known as Block Zero or Block 0. It is an ancestor that every Blockchain network’s block that can be traced to its origin back. Remember how every block in the Blockchain is linked back to the previous block using the hash in the block header? You keep going back, and you realize every block is hence connected to the genesis block.

Our Genesis Block contains the following fields or properties.

  1. timestamp
  2. lastHash
  3. hash
  4. data

So, if we combine all these properties into one object, then it will become a Genesis Block. So based on this block, we will mine the second block. Then from the second block, we will extract the third block and so on. That is why we need a Genesis Block to start a Blockchain.

Now, let us start a project by creating a project folder and then start building awesome blockchain using Javascript.

Step 1: Create a project and create a Genesis Data

The first step is to create a project. Type the following command.

mkdir cryptochain

Go inside that folder.

cd cryptochain

Now, generate the package.json file in the case in future, we need to install any node modules.

npm init -y

Remember, I am using Node v11.3.0. 

Next step is to create a new file inside the root called genesis.js and add the following code.

// genesis.js

const GENESIS_DATA = {
    timestamp: Date.now(),
    lastHash: '64b7edc786326651e031a4d12d9838d279571946d8c9a5d448c70db94b0e143f',
    hash: 'c671c84681b9d682b9fd43b2a2ef01a343eab7cfa410df9835f8165007d38467',
    data: 'krunal'
};

module.exports = { GENESIS_DATA };

Here, we have taken an object with its initial values.

As I have defined earlier, our block contains the four properties. This is a genesis data, so we need to hardcode this values.

The properties timestamp and data are you can understand. But I have used SHA256 algorithm to convert the simple text into hash text.

Actual text for lastHash is a krunal, and actual text for the hash is a krunalHash.

You can verify it by going to this URL: https://passwordsgenerator.net/sha256-hash-generator/

Here, you can enter my name as a text, and it will give the SHA256 hash of that text. Now, you need to convert that text to lowercase by using Javascript’s toLowercase(). That is it. You will find the exact hash like me. Cool!! So now, you have Genesis Data is ready. The next thing is to create a Block from this data.

Step 2: Create a Block

Inside your project root, create a file called block.js and add the following code.

// block.js

const { GENESIS_DATA } = require('./genesis.js');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }
}

module.exports = Block;

So, here we have imported the GENESIS_DATA for our block.

Then we have defined the Block class and passed the parameters to the constructor when we create an object of the Block.

We have also defined the static method called genesis() which is responsible for returning the Genesis Block for our blockchain.

Remember, we have previously defined the GENESIS_DATA not block. After creating an object of this class, it will become a Genesis Block.

Step 3: Create a hash based on a previous block.

We need to define a function that can create a hash based on the previous block’s hash.

So, first let us create a new file inside the root called crypto-hash.js and add the following code inside it.

// crypto-hash.js

const crypto = require('crypto');

const cryptoHash =(...inputs) => {
    const hash = crypto.createHash('sha256');
    hash.update(inputs.sort().join(' '));
    return hash.digest('hex');
}

module.exports = cryptoHash;

Now, to create a Hash, we need the three properties.

  1. timestamp
  2. lastHash
  3. data

So, we have first required the crypto module provided by the Node.js.

Then we have defined the function called cryptoHash() which will accept the inputs. Here we have used spread operator which is the syntax of ES6.

Inside that function, we have called the createHash() method and pass the sha256 as a parameter. That means we need to create a hash based on the sha256 algorithm.

Then we have sorted and join that three parameters and return its hex values.

So, finally, we can get the current block’s hash based on the previous block’s three properties.

Step 4: Mine a new Block based on a previous Block

So, we got the Genesis Block and the hash of that block. Now, we need to write the function that can generate a new Block based on the previous block. Right now, in our case, it is a Genesis Block.

Now, import the crypto-hash module inside the block.js file and create a new function called mineBlock() and pass the two parameters.

  1. lastBlock
  2. data

So, our final block.js file looks like this.

// block.js

const { GENESIS_DATA } = require('./genesis.js');
const cryptoHash = require('./crypto-hash');

class Block {
    constructor({timestamp, lastHash, hash, data}) {
        this.timestamp = timestamp;
        this.lastHash = lastHash;
        this.hash = hash;
        this.data = data;
    }

    static genesis() {
        return new this(GENESIS_DATA);
    }

    static mineBlock({lastBlock, data}) {
        const timestamp = Date.now();
        const lastHash = lastBlock.hash;
        return new this({
            timestamp,
            lastHash,
            data,
            hash: cryptoHash(timestamp, lastHash, data)
        });
    }
}
module.exports = Block;

So, here we have defined the method called mineBlock and pass the two parameters. The mineBlock() will return a complete new Block based on the previous block.

Now, it is the time to create a Blockchain from these blocks.

Step 5: Create a Blockchain

We have completed the step of creating a Genesis Block and mining a new Block. Now it is the time to develop a blockchain. That is why create a new file inside the root called blockchain.js and add the following code inside it.

// blockchain.js

const Block = require('./block');

class Blockchain {

    constructor() {
        this.chain = [Block.genesis()];
    }

    addBlock({ data }) {
        const newBlock = Block.mineBlock({
            lastBlock: this.chain[this.chain.length-1],
            data
        });

        this.chain.push(newBlock);
    }
}

module.exports = Blockchain;

So, first, we have imported the Block.js file and then create a class called Blockchain.

The Blockchain class is responsible for adding a new block inside the blockchain.

The blockchain is an array of the blocks starts with Genesis block.

So in the constructor, we have not defined an empty array. Instead, we have filled the chain array with the Genesis block.

Then we have defined one function called addBlock() which accepts the data.

Now, before adding a new block to the chain array, we need to mine it. That is why we have called the Block class’s mineBlock() method to extract a new block.

For mining a new block, we need a previous block and data. That is why we have used this code this.chain[this.chain.length-1] because it will return the last block in the blockchain and data is already we are passing to that function. So we get the new block based on the previous block and data.

Next step is to add that newly mined block inside our blockchain, and that is it.

The last step is to run this project and get the blockchain.

Step 6: Run the project and get the blockchain.

Now, the last step is to create a file inside the root of the project called server.js and add the following code.

// server.js

const Blockchain = require('./blockchain');
const Block = require('./block');

const blockchain = new Blockchain();

for(let i=0; i<5; i++) {
    const newData = 'krunal'+i;
    blockchain.addBlock({data: newData});
}

console.log(blockchain);

So, here we have imported both the block.js and blockchain.js file and created an object of the Blockchain.

Then we will loop through that blockchain and add the data to that blockchain and created the six blocks in the blockchain because one is Genesis and five based on previous blocks.

Go to the terminal and start the node server.

node server

You will see an output like this.

 

How To Create Blockchain In JavaScript

Finally, How To Create Blockchain In JavaScript Tutorial With Example is over. Now you have a clear understanding of Blockchain technology and how we can start coding in it. Above example is an elementary example of implementing a blockchain. Real-world examples are very complicated but this is the first step to enter the blockchain world and become a blockchain developer.

Github Code

The post How To Create Blockchain In JavaScript appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/15/how-to-create-blockchain-in-javascript/feed/ 1
Node Streams Tutorial With Example https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/ https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/#respond Wed, 28 Nov 2018 23:46:52 +0000 http://localhost/wordpress/?p=2366 Node Streams Tutorial With Example

Node Streams Tutorial With Example is today’s leading topic. Streams are collections of data just like the arrays or strings. The difference between arrays and streams is that streams might not be available all at once, and they don’t have to fit in the memory. This feature makes streams more powerful when working with the massive amounts […]

The post Node Streams Tutorial With Example appeared first on AppDividend.

]]>
Node Streams Tutorial With Example

Node Streams Tutorial With Example is today’s leading topic. Streams are collections of data just like the arrays or strings. The difference between arrays and streams is that streams might not be available all at once, and they don’t have to fit in the memory. This feature makes streams more powerful when working with the massive amounts of data, or the data that is coming from the external source one chunk at a time. Many of the built-in modules in Node implement the streaming interface. So Stream data are not available at once, but they are available at some point of time in the form of chunk data. That is why it is beneficial for developing a streaming web application like Netflix or Youtube.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node Streams Tutorial With Example

I am using node.js version v11.3.0, and your version might be v10, but it does not matter here. The Stream is an abstract interface for working with streaming data in the Node.js. The stream module provides the base API that makes it easy to build the objects that implement the stream interface. 

Streams can be readable, writable, or both.  All streams are instances of EventEmitter.

The following statement can access the stream module.

const stream = require('stream');

Why Streams

Streams primarily provide the following advantages.

  • Memory efficiency: You don’t need to carry the massive amounts of data in memory before you can process it.
  • Time efficiency: It takes way less time to start processing the data as soon as you have it, rather than waiting till the whole data payload is available to start the process.

Types of Streams

There are four fundamental stream types in Node.js:

Let us take a basic simple example of filesystem module streams.

Create a project folder using the following command.

mkdir streams

Go inside that folder and create a file called the server.js and add the following code.

// server.js

const http = require('http')
const fs = require('fs')

const server = http.createServer(function (req, res) {
  fs.readFile('data.txt', (err, data) => {
    res.end(data)
  })
})
server.listen(3000, () => {
  console.log('server is running')
})

Here, we have used the http module to create a web server and also imported the module called fs which is the filesystem module for node.js applications.

When the server starts, we are reading the content of the file data.txt and send the response to that data to a client.

So, we can see the output inside the browser.

Save that file and also create one more file inside the root called data.txt and add the following code in it.

// data.txt

node streams
file streams

Go to the terminal and start the node server using the following command.

node server

Switch to the browser and go to this URL: http://localhost:3000/

We can see the content of the data.txt file.

Here, one thing you can note that when the reading of the file is completed then and then it will send a response. So, if the file is very big, then it takes some time to read the whole file and then sending back to the client.

We can overcome this problem by using the Stream. As we have discussed earlier that streams can emit the chunks of data to the client at some time interval. So, as soon as some chunk of data read, it will emit to the client.

We can use the Streams in the above example like this.

// server.js

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream('data.txt')
  stream.pipe(res)
})
server.listen(3000, () => {
  console.log('Node.js stream on port 3000');
});

Instead of waiting until the file is totally read, we can start streaming it to the HTTP client as soon as we have the chunk of data ready to be sent.

#Example 2

Let us take a second example of Node.js Stream. Write the following code inside a server.js file.

// server.js

const fs = require('fs')

let data = ''

const readerStream = fs.createReadStream('data.txt')

readerStream.setEncoding('UTF8')

readerStream.on('data', (chunk) => {
   data += chunk
})

readerStream.on('end',() => {
   console.log(data)
})

readerStream.on('error', (err) => {
   console.log(err.stack)
})

console.log('Node readerStream');

Here, we get the output inside the terminal because we have not used any web server. This example is an instance of a node eventemitter.

  • data − This event is fired when there is data available for read.

  • end − This event is fired when there is no more data to read.
  • error − This event is fired when there is an error receiving or writing data.
  • finish − This event is fired when all the data has been flushed to the underlying system.

Writable Streams

Write the following code inside a server.js file.

// server.js

const fs = require('fs')

const data = 'Writable Stream Example'

const writerStream = fs.createWriteStream('write.txt')

writerStream.write(data,'UTF8')

writerStream.end()

writerStream.on('finish', function() {
   console.log('Writing completed');
})

writerStream.on('error', function(err) {
   console.log(err.stack)
})

console.log('Streaming Ended')

When the server starts, if the file is not there, it will create it and write the data inside it, and then when the writing is over, we can see the output inside the terminal as well as inside the newly created file.

Piping the Streams

Piping is a mechanism where we provide the output of one stream as the input to another stream. It is usually used to get data from one stream and to pass the output of that stream to another stream.

// server.js

const fs = require('fs')

const readerStream = fs.createReadStream('data.txt')

const writerStream = fs.createWriteStream('data2.txt')

readerStream.pipe(writerStream)

console.log('Piping ended')

So, here, we are reading the data from the data.txt file and writing the data to the other file called data2.txt.

We have piped the readerStream to writerStream.

Difference between fs.readFile() and fs.createReadStream()

The fs.readFile() loads file and reads it into memory and then writes it to response whereas fs.createReadStream() sends chunks of file like writing small chunks of file dividing the entire process into that chunk size of file writing which reduces memory load and memory wastage/garbage reduction.

Finally, Node Streams Tutorial With Example is over.

The post Node Streams Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/feed/ 0
React CRUD Example | MERN Stack Tutorial https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/ https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/#comments Sun, 11 Nov 2018 20:23:48 +0000 http://localhost/wordpress/?p=2141 React CRUD Example Tutorial From Scratch

React CRUD Example | MERN Stack Tutorial is today’s leading topic. This article’s goal is to explain the by making the CRUD application. Most applications are CRUD applications. If you don’t know what CRUD is, it’s short for Create, Read, Update and Delete. This application is also called a MERN Stack application because we are using MongoDB, Express, […]

The post React CRUD Example | MERN Stack Tutorial appeared first on AppDividend.

]]>
React CRUD Example Tutorial From Scratch

React CRUD Example | MERN Stack Tutorial is today’s leading topic. This article’s goal is to explain the by making the CRUD application. Most applications are CRUD applications. If you don’t know what CRUD is, it’s short for Create, Read, Update and Delete. This application is also called a MERN Stack application because we are using MongoDB, Express, React, and Node.js tech stack. This article will show you the steps to create an app where the user can create new business, fetch that business, edit business and delete business using React.js. Let us understand the basics of React.js.

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.

What is React?

React.js is UI Library and not a complete Framework like Angular. React is the JavaScript library for building user interfaces. It is maintained by Facebook, Instagram and a community of individual developers and corporations. You can find its official documentation here.

Why use React?

React.js allows you to express how your app should look at any given point in time. React will automatically manage all UI updates when your underlying data changes. When the data changes, React conceptually hits the “refresh” button and knows to only update the changed parts. The main reason to use React for your next project is following.

  1. Fast Learning Curve.
  2. Reusable Components.
  3. Fast render with Virtual DOM.
  4. Clean Abstraction.
  5. Redux: A State Management Library For Complex UIs.
  6. Great Developer Tools.
  7. React Native: You can build a cross-platform native mobile application for Android or iOS.

Who uses React?

Aside from Facebook and Instagram, many well-known companies use React including Dropbox, PayPal, Netflix, Airbnb and many more.

MERN Stack Tutorial

We will use the following Technologies with its version.

  1. MacOS (Mojave)
  2. Node v10.11.0
  3. NPM v6.4.1
  4. MongoDB shell version v3.6.3
  5. MongoDB version v3.6.3
  6. React.js version 16.6.1

React CRUD Example

Create a new React app using the following command.

#1: Install React Application

npx create-react-app reactcrud
cd reactcrud
npm start

 

React CRUD Example

If you are facing any issue on compiling then, please create a .env file on the root and add the following line of code.

SKIP_PREFLIGHT_CHECK=true

Go to this URL: http://localhost:3000/

 

MERN Stack Tutorial

Now, install the Bootstrap 4 Framework using the following command.

yarn add bootstrap

# or

npm install bootstrap --save

Import the Bootstrap CSS Framework inside our project.

Modify the code inside the src >> App.js file.

// App.js

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <div className="container">
        <h2>React CRUD Tutorial</h2>
      </div>
    );
  }
}

export default App;

Save the file and go to the browser and you can see that we have successfully integrated bootstrap 4 in our react application.

#2: Configure React routing

Type the following command to install the react- router-dom module. If you want to find more information about the react-router-dom module, then you can follow this documentation.

yarn add react-router-dom

# or

npm install react-router-dom --save

Go to the index.js file and Wrap the BrowserRouter object around the App.js component.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <BrowserRouter>
  <App />
  </BrowserRouter>, document.getElementById('root'));

serviceWorker.unregister();

Now, create three components.

Inside the src folder, create one directory called components and inside that folder, make three components.

  1. create.component.js
  2. edit.component.js
  3. index.component.js
// create.component.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Create Component!!</p>
            </div>
        )
    }
}
// edit.component.js

import React, { Component } from 'react';

export default class Edit extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Edit Component!!</p>
            </div>
        )
    }
}
// index.component.js

import React, { Component } from 'react';

export default class Index extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Index Component!!</p>
            </div>
        )
    }
}

Now, add the navigation bar in our React CRUD example. Write a following code inside the App.js file.

// App.js

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

import Create from './components/create.component';
import Edit from './components/edit.component';
import Index from './components/index.component';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">
          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <Link to={'/'} className="navbar-brand">React CRUD Example</Link>
            <div className="collapse navbar-collapse" id="navbarSupportedContent">
              <ul className="navbar-nav mr-auto">
              <li className="nav-item">
                  <Link to={'/'} className="nav-link">Home</Link>
                </li>
                <li className="nav-item">
                  <Link to={'/create'} className="nav-link">Create</Link>
                </li>
                <li className="nav-item">
                  <Link to={'/index'} className="nav-link">Index</Link>
                </li>
              </ul>
            </div>
          </nav> <br/>
          <h2>Welcome to React CRUD Tutorial</h2> <br/>
          <Switch>
              <Route exact path='/create' component={ Create } />
              <Route path='/edit/:id' component={ Edit } />
              <Route path='/index' component={ Index } />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Save the file and go to the browser.

 

React CRUD Tutorial

#3: Create the bootstrap form

Write the code to generate the bootstrap form inside the create.component.js file.

// create.component.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div style={{marginTop: 10}}>
                <h3>Add New Business</h3>
                <form>
                    <div className="form-group">
                        <label>Add Person Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Business Name: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add GST Number: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Register Business" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

 

MERN Stack Example

#4: Submit the Form

Okay, now we have three fields.

  1. person name
  2. business name
  3. gst number

So we need to create four functions that can track the values of the textbox and set that state according to it. Also, the fourth function will send the POST request to the node express server.

Now, first, we will define the constructor and set the initial state and then also bind this to the different events inside the constructor.

Then define the different functions with each input text values. So when the user types inside the textbox, we set the state according to it.

So, let say, the user is typing the person name inside the textbox, we are changing the state value of person name. Finally, same for all of the inputs and when we submit the form, we get the values from the state and send to the POST request.

// App.js

import React, { Component } from 'react';

export default class Create extends Component {
  constructor(props) {
      super(props);
      this.onChangePersonName = this.onChangePersonName.bind(this);
      this.onChangeBusinessName = this.onChangeBusinessName.bind(this);
      this.onChangeGstNumber = this.onChangeGstNumber.bind(this);
      this.onSubmit = this.onSubmit.bind(this);

      this.state = {
          person_name: '',
          business_name: '',
          business_gst_number:''
      }
  }
  onChangePersonName(e) {
    this.setState({
      person_name: e.target.value
    });
  }
  onChangeBusinessName(e) {
    this.setState({
      business_name: e.target.value
    })  
  }
  onChangeGstNumber(e) {
    this.setState({
      business_gst_number: e.target.value
    })
  }

  onSubmit(e) {
    e.preventDefault();
    console.log(`The values are ${this.state.person_name}, ${this.state.business_name}, and ${this.state.business_gst_number}`)
    this.setState({
      person_name: '',
      business_name: '',
      business_gst_number: ''
    })
  }
 
  render() {
      return (
          <div style={{ marginTop: 10 }}>
              <h3>Add New Business</h3>
              <form onSubmit={this.onSubmit}>
                  <div className="form-group">
                      <label>Person Name:  </label>
                      <input 
                        type="text" 
                        className="form-control" 
                        value={this.state.person_name}
                        onChange={this.onChangePersonName}
                        />
                  </div>
                  <div className="form-group">
                      <label>Business Name: </label>
                      <input type="text" 
                        className="form-control"
                        value={this.state.business_name}
                        onChange={this.onChangeBusinessName}
                        />
                  </div>
                  <div className="form-group">
                      <label>GST Number: </label>
                      <input type="text" 
                        className="form-control"
                        value={this.state.business_gst_number}
                        onChange={this.onChangeGstNumber}
                        />
                  </div>
                  <div className="form-group">
                      <input type="submit" value="Register Business" className="btn btn-primary"/>
                  </div>
              </form>
          </div>
      )
  }
}

#5: Create a backend on Node.js

Inside our reactcrud project root, create one folder called api and go inside that folder and initialize the package.json file.

npm init -y

Now, install the following node.js dependencies.

yarn add express body-parser cors mongoose

# or

npm install express body-parser cors mongoose --save

Also, install the nodemon as a development dependency. So that we do not need to restart every time, we change our server code.

npm install nodemon --save-dev

Now, inside the api folder, create one file called the server.js and add the following code inside it.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');

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

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});

Save the file and open a new tab terminal inside the api folder and hit the following command to spin up the node.js server.

nodemon server

You can see inside the terminal that, our node.js server is running.

React CRUD Example | MERN Stack Tutorial

 

#6: Setup a MongoDB database

If you are a beginner in MongoDB database, then please check out by below tutorial.

Related Post: NoSQL MongoDB Tutorial

I have already installed the MongoDB on Mac. So I am starting the MongoDB server by the following command.

mongod

Inside the api folder, create one file called the DB.js and add the following line of code.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/reactcrud'
}

In my local MongoDB database, the username and password are empty, but in the production, you need to create one admin user and assign the database to that user.

Now, import this DB.js file into the server.js file.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

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

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});

Save the file, and you can see inside the terminal that our node.js application is connected to a mongodb database.

#7: Create a Mongoose Schema

Next step is that we need to create a schema for the mongodb database. For that, create a file inside the api project root called business.model.js and add the following code.

// business.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Business
let Business = new Schema({
  person_name: {
    type: String
  },
  business_name: {
    type: String
  },
  business_gst_number: {
    type: Number
  }
},{
    collection: 'business'
});

module.exports = mongoose.model('Business', Business);

We have taken three fields called person_name, business_name, and business_gst_number with its datatypes.

#8: Define the route for Node.js Express application

Write the CRUD code inside the business.route.js file.

// business.route.js

const express = require('express');
const businessRoutes = express.Router();

// Require Business model in our routes module
let Business = require('./business.model');

// Defined store route
businessRoutes.route('/add').post(function (req, res) {
  let business = new Business(req.body);
  business.save()
    .then(business => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
    Business.find(function(err, businesses){
    if(err){
      console.log(err);
    }
    else {
      res.json(businesses);
    }
  });
});

// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Business.findById(id, function (err, business){
      res.json(business);
  });
});

//  Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
    Business.findById(req.params.id, function(err, business) {
    if (!business)
      res.status(404).send("data is not found");
    else {
        business.person_name = req.body.person_name;
        business.business_name = req.body.business_name;
        business.business_gst_number = req.body.business_gst_number;

        business.save().then(business => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
    Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = businessRoutes;

Here, we have defined the CRUD operations for MongoDB. So when the request hits the server, it maps the URI and according to URI, the above function will be executed, and database operation will be performed and send the response to the client.

Here, we have used a Mongoose ORM to save, update, delete the data from the database. Mongoose is an ORM used in MongoDB database. Now, we have all the CRUD operations set up on the route file; we need to import inside the server.js file.

So, our final server.js file looks like this.

// server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const businessRoute = require('./business.route');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

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

app.use('/business', businessRoute);

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});

Save the file and see the terminal and check if we got any errors.

#9: Install Axios library and send a POST request.

Install the Axios library and send the POST request. If you want to learn about the Axios library, then check out my Getting Started With Axios Promise Based HTTP Client Tutorial Example article.

yarn add axios

# or

npm install axios --save

Now, send the HTTP POST request along with the form data to the node js server. We will send the data as an object because we have used the body-parser at the backend to pluck the data from the request and save it in the database.

Write the following code inside the create.component.js file.

// create.component.js

import React, { Component } from 'react';
import axios from 'axios';

export default class Create extends Component {
  constructor(props) {
    super(props);
    this.onChangePersonName = this.onChangePersonName.bind(this);
    this.onChangeBusinessName = this.onChangeBusinessName.bind(this);
    this.onChangeGstNumber = this.onChangeGstNumber.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
      person_name: '',
      business_name: '',
      business_gst_number:''
    }
  }
  onChangePersonName(e) {
    this.setState({
      person_name: e.target.value
    });
  }
  onChangeBusinessName(e) {
    this.setState({
      business_name: e.target.value
    })  
  }
  onChangeGstNumber(e) {
    this.setState({
      business_gst_number: e.target.value
    })
  }

  onSubmit(e) {
    e.preventDefault();
    const obj = {
      person_name: this.state.person_name,
      business_name: this.state.business_name,
      business_gst_number: this.state.business_gst_number
    };
    axios.post('http://localhost:4000/business/add', obj)
        .then(res => console.log(res.data));
    
    this.setState({
      person_name: '',
      business_name: '',
      business_gst_number: ''
    })
  }
 
  render() {
    return (
        <div style={{ marginTop: 10 }}>
            <h3>Add New Business</h3>
            <form onSubmit={this.onSubmit}>
                <div className="form-group">
                    <label>Person Name:  </label>
                    <input 
                      type="text" 
                      className="form-control" 
                      value={this.state.person_name}
                      onChange={this.onChangePersonName}
                      />
                </div>
                <div className="form-group">
                    <label>Business Name: </label>
                    <input type="text" 
                      className="form-control"
                      value={this.state.business_name}
                      onChange={this.onChangeBusinessName}
                      />
                </div>
                <div className="form-group">
                    <label>GST Number: </label>
                    <input type="text" 
                      className="form-control"
                      value={this.state.business_gst_number}
                      onChange={this.onChangeGstNumber}
                      />
                </div>
                <div className="form-group">
                    <input type="submit" value="Register Business" className="btn btn-primary"/>
                </div>
            </form>
        </div>
    )
  }
}

Now, submit the form with proper values and open your browser console panel and see the response.

 

React CRUD Project

Also, now check inside the mongodb database and see the values.

To see the values inside the database, we can start a mongoshell and look at the values in the database.

 

Mongo CRUD

So, we can see that our data is added successfully.

#10: Display the backend data

Write the following code inside the index.component.js file.

// index.component.js

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';

export default class Index extends Component {

  constructor(props) {
      super(props);
      this.state = {business: []};
    }
    componentDidMount(){
      axios.get('http://localhost:4000/business')
        .then(response => {
          this.setState({ business: response.data });
        })
        .catch(function (error) {
          console.log(error);
        })
    }
    tabRow(){
      return this.state.business.map(function(object, i){
          return <TableRow obj={object} key={i} />;
      });
    }

    render() {
      return (
        <div>
          <h3 align="center">Business List</h3>
          <table className="table table-striped" style={{ marginTop: 20 }}>
            <thead>
              <tr>
                <th>Person</th>
                <th>Business</th>
                <th>GST Number</th>
                <th colSpan="2">Action</th>
              </tr>
            </thead>
            <tbody>
              { this.tabRow() }
            </tbody>
          </table>
        </div>
      );
    }
  }

So, here, we have sent the GET request to the node.js server and fetch that data from an API.

We have imported the TableRow.js component. So let us create that component. Inside the components folder, create one more component called TableRow.js and add the following code inside it.

// TableRow.js

import React, { Component } from 'react';

class TableRow extends Component {
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.person_name}
          </td>
          <td>
            {this.props.obj.business_name}
          </td>
          <td>
            {this.props.obj.business_gst_number}
          </td>
          <td>
            <button className="btn btn-primary">Edit</button>
          </td>
          <td>
            <button className="btn btn-danger">Delete</button>
          </td>
        </tr>
    );
  }
}

export default TableRow;

This component is responsible for display the row data fetched from the backend.

Save the file and go to the browser and see this URL: http://localhost:3000/index.

 

React Node Example

#11: Edit and Update Functionality

First, add the Link to the TableRow.js file.

// TableRow.js

import { Link } from 'react-router-dom';

<Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Edit</Link>

Add the following code to the edit.component.js file.

// edit.component.js

import React, { Component } from 'react';
import axios from 'axios';

export default class Edit extends Component {
  constructor(props) {
    super(props);
    this.onChangePersonName = this.onChangePersonName.bind(this);
    this.onChangeBusinessName = this.onChangeBusinessName.bind(this);
    this.onChangeGstNumber = this.onChangeGstNumber.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
      person_name: '',
      business_name: '',
      business_gst_number:''
    }
  }

  componentDidMount() {
      axios.get('http://localhost:4000/business/edit/'+this.props.match.params.id)
          .then(response => {
              this.setState({ 
                person_name: response.data.person_name, 
                business_name: response.data.business_name,
                business_gst_number: response.data.business_gst_number });
          })
          .catch(function (error) {
              console.log(error);
          })
    }

  onChangePersonName(e) {
    this.setState({
      person_name: e.target.value
    });
  }
  onChangeBusinessName(e) {
    this.setState({
      business_name: e.target.value
    })  
  }
  onChangeGstNumber(e) {
    this.setState({
      business_gst_number: e.target.value
    })
  }

  onSubmit(e) {
    e.preventDefault();
    const obj = {
      person_name: this.state.person_name,
      business_name: this.state.business_name,
      business_gst_number: this.state.business_gst_number
    };
    axios.post('http://localhost:4000/business/update/'+this.props.match.params.id, obj)
        .then(res => console.log(res.data));
    
    this.props.history.push('/index');
  }
 
  render() {
    return (
        <div style={{ marginTop: 10 }}>
            <h3 align="center">Update Business</h3>
            <form onSubmit={this.onSubmit}>
                <div className="form-group">
                    <label>Person Name:  </label>
                    <input 
                      type="text" 
                      className="form-control" 
                      value={this.state.person_name}
                      onChange={this.onChangePersonName}
                      />
                </div>
                <div className="form-group">
                    <label>Business Name: </label>
                    <input type="text" 
                      className="form-control"
                      value={this.state.business_name}
                      onChange={this.onChangeBusinessName}
                      />
                </div>
                <div className="form-group">
                    <label>GST Number: </label>
                    <input type="text" 
                      className="form-control"
                      value={this.state.business_gst_number}
                      onChange={this.onChangeGstNumber}
                      />
                </div>
                <div className="form-group">
                    <input type="submit" 
                      value="Update Business" 
                      className="btn btn-primary"/>
                </div>
            </form>
        </div>
    )
  }
}

So, what we have done is, we have used the component lifecycle method to fetch the data from the API.

That data needs to be displayed inside the textbox because this is edit form. Next, it is the same thing as we have written the code in the create.component.js file.

Save the file and go to the edit page from the index or listing page. If the data is not displayed then please first check that you have the running node.js server on the backend.

 

React MongoDB Example

We have also written the code that will update the data because we have written the function that will send the request to the node.js server and update the data based on the ID.

#12: Delete the data

Now, the only thing remaining is to delete the data. So define the delete function inside TableRow.js file.

// TableRow.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class TableRow extends Component {

  constructor(props) {
        super(props);
        this.delete = this.delete.bind(this);
    }
    delete() {
        axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
            .then(console.log('Deleted'))
            .catch(err => console.log(err))
    }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.person_name}
          </td>
          <td>
            {this.props.obj.business_name}
          </td>
          <td>
            {this.props.obj.business_gst_number}
          </td>
          <td>
            <Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Edit</Link>
          </td>
          <td>
            <button onClick={this.delete} className="btn btn-danger">Delete</button>
          </td>
        </tr>
    );
  }
}

export default TableRow;

Now, we have completed React CRUD Example or MERN Stack Tutorial From Scratch.

I have put this code on Github. So you can check that code as well.

Finally, React CRUD Example Tutorial is over. Thanks for taking.

Github Code

The post React CRUD Example | MERN Stack Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/11/react-crud-example-mern-stack-tutorial/feed/ 46
Angular 7 CRUD Example | MEAN Stack Tutorial From Scratch https://appdividend.com/2018/11/04/angular-7-crud-example-mean-stack-tutorial/ https://appdividend.com/2018/11/04/angular-7-crud-example-mean-stack-tutorial/#comments Sun, 04 Nov 2018 19:44:17 +0000 http://localhost/wordpress/?p=2079 Angular 7 CRUD Tutorial with Example From Scratch

Angular 7 CRUD Example | MEAN Stack Tutorial is today’s leading topic. In this article, we will be creating a sample Angular 7 application step by step from scratch and perform CRUD operations. The backend API will be exposed using Node.js, and Express framework and MongoDB will be used for persistent storage of the data. We will […]

The post Angular 7 CRUD Example | MEAN Stack Tutorial From Scratch appeared first on AppDividend.

]]>
Angular 7 CRUD Tutorial with Example From Scratch

Angular 7 CRUD Example | MEAN Stack Tutorial is today’s leading topic. In this article, we will be creating a sample Angular 7 application step by step from scratch and perform CRUD operations. The backend API will be exposed using Node.js, and Express framework and MongoDB will be used for persistent storage of the data. We will be using Angular CLI 7 to generate the boilerplate project. This Angular 7 CRUD Example Tutorial is the comprehensive guide on building CRUD (Create, Read, Update, Delete) Web Application using the New Angular 7 Framework. The Angular 7 just released and it comes with a few new feature and improvements.

If you want to learn more about Angular, then check out this Angular 7 – The complete Guide course.

Angular 7 Features and Upgrades

Angular 7 got released this year in October with multiple new features such as CLI Prompts, Virtual Scroll, Drag and Drop, Angular Budgets and many more. From this release, Angular supports Node 10 and simultaneously maintains Node 8 support with TypeScript 3.1 and RxJS 6.3. A new extension from @angular/schematics called prompts has been introduced with the CLI that will now prompt developers when running common commands such as ng new my-app. Following are the list of the new Angular 7 features and upgrades.

  1. A new ng-compiler
  2. CLI prompts
  3. Angular DoBootstrap
  4. Application performance is increased
  5. ScrollingModule and DragDropModule
  6. Ivy Renderer
  7. TypeScript 3.1
  8. RxJS 6.3

Workflow of Angular 7 Tutorial

We will create two separate projects. One is for Angular, and one is for Node.js | Express | MongoDB. That means one for frontend and one for the backend. We will create a backend API, and frontend will consume that API. For this example, I am using the following tech stacks and their versions.

  1. Node v10.11.0
  2. NPM v6.4.1
  3. AngularCLI v7.0.2
  4. MongoDB shell version v3.6.3
  5. MongoDB version v3.6.3
  6. Mac OS Mojave

Angular 7 CRUD Example | MEAN Stack Tutorial

First, we will install Angular 7 using Angular CLI, and then we will continue to develop the frontend and backend.

#1: Install Angular 7 and other dependencies.

If you have an older @angular/cli version, then you can run the following command to install the latest versions.

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli

If you are going through any issues, then please check out my this How To Update Angular CLI To Version 7It will help you to update your Angular CLI, and you will be able to create a brand new Angular seven project.

Okay, now if you type the following command, you can see that we have updated Angular CLI.

 

Angular 7 CRUD Example | MEAN Stack Tutorial

Now, you will be able to create a new Angular project using the following command.

ng new angular7crud
cd angular7crud

 

MEAN Stack CRUD Example

After going inside the project folder, open the project in Visual Studio Code using the following command. If you are not using it, then start using it. It is the best Editor for Javascript development.

code .

At the time of installation, we have enabled to routing for our application. It is new in Angular 7 because it will prompt us while installing angular boilerplate. You can check the file called app-routing.module.ts file inside src >> app directory.

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add it inside the angular.json file.

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
 ],

So, now we can use the Bootstrap 4 classes in our project. 

Start the Angular development server using the following command.

ng serve -o

 

Angular 7 Tutorial

Project Description

We will create a project, where the user can enter their User Name, Business Name, and GST Number from the form and submit the form. If the values are incorrect, then it will validate at the frontend and form will not submit. If all the values seem perfect, then we will be able to send the form to backend API, and it will store the values inside the MongoDB database.

So now, we will create some angular components to do the job.

#2: Generate Angular Components

Type the following command to generate Angular 7 Components. We will perform create, read, update operations. So we will create three components.

ng g c gst-add --spec=false
ng g c gst-get --spec=false
ng g c gst-edit --spec=false

 

Angular CRUD Tutorial

All the three components are automatically registered inside an app.module.ts file. Now, we need to configure the routing of angular components inside an app-routing.module.ts file.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { GstAddComponent } from './gst-add/gst-add.component';
import { GstEditComponent } from './gst-edit/gst-edit.component';
import { GstGetComponent } from './gst-get/gst-get.component';

const routes: Routes = [
  {
    path: 'business/create',
    component: GstAddComponent
  },
  {
    path: 'business/edit/:id',
    component: GstEditComponent
  },
  {
    path: 'business',
    component: GstGetComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

Now, you can see inside the app.component.html file that <router-outlet> directive is there. This directive helps us to render the different component based on the route URI.

#3: Create an Angular Navigation

Write the following code inside the app.component.html file.

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Save the file and go to the browser and click on two links. You can see that we can see the different components based on the navigation.

#4: Install Angular Routing Progress Indicator.

Type the following command to install the ng2-slim-loading-bar library.

npm install ng2-slim-loading-bar --save

So, if you install third-party packages right now, then it is not compatible with Angular 7. To bridge the gap between Angular 7 and third-party packages, we need to install the following library. That is it.

npm install rxjs-compat --save

Now, import the SlimLoadingBarModule inside the app.module.ts file.

// app.module.ts

import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';

imports: [
    ...
    SlimLoadingBarModule
],

Next step is, include the styling that comes with the library inside src  >>  styles.css file.

@import "../node_modules/ng2-slim-loading-bar/style.css";

#5: Adding Router Events.

Angular RouterModule gives us the following event modules.

  1. NavigationStart
  2. NavigationEnd
  3. NavigationError
  4. NavigationCancel
  5. Router
  6. Event

Now, write the following code inside the  app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import {SlimLoadingBarService} from 'ng2-slim-loading-bar';
import { NavigationCancel,
        Event,
        NavigationEnd,
        NavigationError,
        NavigationStart,
        Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular7crud';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) => {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}

What it is doing that it intercepts the routing event and add the loading bar component to every route so that we can see the routing indication every time we change the routes.

The final change to display routing indicator is that we need to add the ng2-slim-loading-bar directive inside the app.component.html file at the top of the page.

<ng2-slim-loading-bar color="blue"></ng2-slim-loading-bar>

<nav class="navbar navbar-expand-sm bg-light">
  <div class="container-fluid">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a routerLink="business/create" class="nav-link" routerLinkActive="active">
          Create Business
        </a>
      </li>
      <li class="nav-item">
        <a routerLink="business" class="nav-link" routerLinkActive="active">
          Business
        </a>
      </li> 
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Save the file and go to the terminal to see if there any error and if not then go to the browser and change the routes, and you can see that now we can see the routing indicator.

#6: Add Bootstrap Form

Inside the gst-add.component.html file, add the following bootstrap 4 form.

<div class="card">
  <div class="card-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <button type="submit" class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

 

Angular 7 CRUD Demo

#7: Add Angular Form Validation

We will use ReactiveFormsModule. So if you are new to Angular Form Validation, then please check out my this article Angular 7 Form Validation Example Tutorial on this blog.

Now, import the ReactiveFormsModule inside the app.module.ts file.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    ...
    ReactiveFormsModule
],

Now, we need to write the code for the app.component.ts file. Remember, this is not template-driven form. So we will change the code inside the app.component.ts file.

First, we import the FormGroup, FormBuilder, Validators modules from @angular/forms.

Also, create a constructor and instantiate the FormBuilder.

So write the following code inside the gst-add.component.ts file.

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  ngOnInit() {
  }

}

We have used form builder to handle all the validation. So in that constructor, we are creating a form with the validation rules. In our example, there are three fields. If input text is empty, then it will give an error, and we need to display that error.

Now, write the following code inside the gst-add.component.html file.

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button type="submit" 
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">Add Business</button>
      </div>
    </form>
  </div>
</div>

Save the file and go to the browser and you can see, if you do not put any value inside the input box, then you will see the errors.

 

Angular 7 Form Validation Example

#8: Configure the HttpClientModule

Import the HttpClientModule inside the app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
   ...
    HttpClientModule
 ],

#9: Create a model.

Inside the src >> app folder, create one file called Business.ts and add the following code.

// Business.ts

export default class Business {
  person_name: String;
  business_name: String;
  business_gst_number: Number;
}

#10: Create an Angular Service file.

Type the following command to generate the service file.

ng g service business --spec=false

So, your primary business.service.ts file looks like this.

// business.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  constructor() { }
}

Now, import the business.service.ts file into the app.module.ts file.

// app.module.ts

import { BusinessService } from './business.service';

providers: [ BusinessService ],

#11: Submit the data to the node server

Now, we need to write the code that will send the HTTP POST request with the data to the Node.js server and save the data into the MongoDB database.

Write the following code inside the business.service.ts file.

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    console.log(obj);
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }
}

We have defined our backend API URL, but we have not created any backend yet, but we will do in a couple of steps.

Now, we need to add the click event to the Add Business Button. So add the following code inside the gst-add.component.html file.

<div class="form-group">
    <button (click)="addBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.pristine || angForm.invalid" 
        class="btn btn-primary">
        Add Business
     </button>
</div>

So when there are no errors, we can submit the form, and it will call the component’s addBusiness function. From there, we will call the angular service and service will send the HTTP Post request to the Node.js server.

Now, add the addBusiness function inside the gst-add.component.ts file. So write the following code inside the gst-add.component.ts file.

// gst-add.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-add',
  templateUrl: './gst-add.component.html',
  styleUrls: ['./gst-add.component.css']
})
export class GstAddComponent implements OnInit {

  angForm: FormGroup;
  constructor(private fb: FormBuilder, private bs: BusinessService) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      person_name: ['', Validators.required ],
      business_name: ['', Validators.required ],
      business_gst_number: ['', Validators.required ]
    });
  }

  addBusiness(person_name, busines_name, business_gst_number) {
    this.bs.addBusiness(person_name, busines_name, business_gst_number);
  }

  ngOnInit() {
  }

}

Here, we have defined the function and also imported the business.service.ts file. Instantiate the object inside the constructor and use that to call the function of the businsess.service.ts file.

We have already coded the addBusiness function inside the business.service.ts file. Now, we need to configure the backend API.

#12: Create a Node.js backend API

Inside the angular root folder, create one folder called api and go inside that folder. Remember, it will be a completely separate project from Angular. So its node_modules are different from an Angular.

Open the terminal inside the api folder and type the following command.

npm init -y

Install the following node specific modules.

npm install --save express body-parser cors mongoose

I do not restart node server each time; I change the file. So I am installing the nodemon server. What it does is that, when I modify the server.js file, it restarts the node.js server automatically.

npm install nodemon --save-dev

Now, inside the api folder, create one file called the server.js file.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose');

    const app = express();
    let port = process.env.PORT || 4000;

    const server = app.listen(function(){
        console.log('Listening on port ' + port);
    });

The next thing is to connect MongoDB database with our node.js application.

If you have not installed the MongoDB database then install it and then start the mongodb server.

Type the following command to start the MongoDB server.

mongod

So, Now, I have connected to the database.

Create one file called DB.js inside api root project folder. Write the following code inside the DB.js file.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/ng7crud'
 };

Import this DB.js file inside our server.js file and use mongoose library to set up the database connection with MongoDB. We can also use Mongoose to save the data in the database using Mongoose ORM.

Write the following code inside the server.js file to connect our MongoDB application to the Node.js server.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

    mongoose.Promise = global.Promise;
    mongoose.connect(config.DB, { useNewUrlParser: true }).then(
      () => {console.log('Database is connected') },
      err => { console.log('Can not connect to the database'+ err)}
    );

    const app = express();
    app.use(bodyParser.json());
    app.use(cors());
    const port = process.env.PORT || 4000;

    const server = app.listen(port, function(){
     console.log('Listening on port ' + port);
    });

Save the file and go to the terminal and start the node server.

nodemon server

So, right now, you have three servers are running.

  1. Angular Development Server
  2. Nodemon server
  3. MongoDB server

Remember all the three servers are running fine without any error otherwise, our application will not work.

#13: Create model and routes for our application.

Now, we need to create two folders inside the api root folder called routes and models.

In models folder, create one model called Business.js.

// Business.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Business
let Business = new Schema({
  person_name: {
    type: String
  },
  business_name: {
    type: String
  },
  business_gst_number: {
    type: Number
  }
},{
    collection: 'business'
});

module.exports = mongoose.model('Business', Business);

So, we have defined our schema for the business collection. We have three fields called person_name, business_name, business_gst_number.

In the routes folder, create one file called the business.route.js.

Write the CRUD code inside the business.route.js file.

// business.route.js

const express = require('express');
const app = express();
const businessRoutes = express.Router();

// Require Business model in our routes module
let Business = require('../models/Business');

// Defined store route
businessRoutes.route('/add').post(function (req, res) {
  let business = new Business(req.body);
  business.save()
    .then(business => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
    Business.find(function (err, businesses){
    if(err){
      console.log(err);
    }
    else {
      res.json(businesses);
    }
  });
});

// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Business.findById(id, function (err, business){
      res.json(business);
  });
});

//  Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
    Business.findById(req.params.id, function(err, next, business) {
    if (!business)
      return next(new Error('Could not load Document'));
    else {
        business.person_name = req.body.person_name;
        business.business_name = req.body.business_name;
        business.business_gst_number = req.body.business_gst_number;

        business.save().then(business => {
          res.json('Update complete');
      })
      .catch(err => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
    Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = businessRoutes;

Here, we have used the mongoose model to save, update, delete the data from the database. Mongoose is an ORM used in MongoDB database. Now, we have all the CRUD operations set up on the route file; we need to import inside the server.js file.

So, our final server.js file looks like this.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    cors = require('cors'),
    mongoose = require('mongoose'),
    config = require('./DB');

const businessRoute = require('./routes/business.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {console.log('Database is connected') },
  err => { console.log('Can not connect to the database'+ err)}
);

const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/business', businessRoute);
const port = process.env.PORT || 4000;

const server = app.listen(port, function(){
  console.log('Listening on port ' + port);
});

#14: Test the store data functionality

If your all the servers are up and running then you can go to the browser and fill the form data and add the business. You can see something like this on your screen if you are successful.

 

MEAN Stack Tutorial

Now, we can check on the database using the following commands.

First, open the mongo shell on the 4th tab because all the other three tabs are occupied at the moment.

mongo

 

MongoDB CRUD

Here, we can see that the values are storing in the MongoDB database. Yess!! We have succeeded.

Now, remaining operations are Read, Update, and Delete.

#15: Display the data on frontend

In the gst-get.component.html file, write the following code.

<table class="table table-hover">
  <thead>
  <tr>
      <td>Person Name</td>
      <td>Business Name</td>
      <td>GST Number</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>

  <tbody>
      <tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['/edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a [routerLink]="" class="btn btn-danger">Delete</a></td>
      </tr>
  </tbody>
</table>

Now, inside the business.service.ts file, we need to write the function that fetches the businesses data from the MongoDB database and display at the Angular application.

// business.service.ts

getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

Now, we need to include this business.service.ts file and Business.ts file inside the gst-get.component.ts file.

Write the following code inside the gst-get.component.ts file.

// gst-get.component.ts

import { Component, OnInit } from '@angular/core';
import Business from '../Business';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-get',
  templateUrl: './gst-get.component.html',
  styleUrls: ['./gst-get.component.css']
})
export class GstGetComponent implements OnInit {

  businesses: Business[];

  constructor(private bs: BusinessService) { }

  ngOnInit() {
    this.bs
      .getBusinesses()
      .subscribe((data: Business[]) => {
        this.businesses = data;
    });
  }
}

Save the file and go to the browser and switch to this URL: http://localhost:4200/business. You can see the listing of the businesses.

#16: Edit and Update Data

Okay, first, we need to fetch the data from the MongoDB database using _id wise and display that data in the gst-edit.component.html file.

So first, write the following code inside the gst-edit.component.ts file.

// gst-edit.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { BusinessService } from '../business.service';

@Component({
  selector: 'app-gst-edit',
  templateUrl: './gst-edit.component.html',
  styleUrls: ['./gst-edit.component.css']
})
export class GstEditComponent implements OnInit {

  business: any = {};
  angForm: FormGroup;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private bs: BusinessService,
    private fb: FormBuilder) {
      this.createForm();
 }

  createForm() {
    this.angForm = this.fb.group({
        person_name: ['', Validators.required ],
        business_name: ['', Validators.required ],
        business_gst_number: ['', Validators.required ]
      });
    }


  ngOnInit() {
    this.route.params.subscribe(params => {
        this.bs.editBusiness(params['id']).subscribe(res => {
          this.business = res;
      });
    });
  }
}

Here, when the gst-edit component.ts render, it will call the ngOnInit method and send an HTTP request to the node server and fetch the data from a _id to display inside the gst-edit.component.html file.

Now, inside the business.service.ts file, we need to code the editBusiness function to send an HTTP request.

// business.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BusinessService {

  uri = 'http://localhost:4000/business';

  constructor(private http: HttpClient) { }

  addBusiness(person_name, business_name, business_gst_number) {
    const obj = {
      person_name: person_name,
      business_name: business_name,
      business_gst_number: business_gst_number
    };
    this.http.post(`${this.uri}/add`, obj)
        .subscribe(res => console.log('Done'));
  }

  getBusinesses() {
    return this
           .http
           .get(`${this.uri}`);
  }

  editBusiness(id) {
    return this
            .http
            .get(`${this.uri}/edit/${id}`);
    }
}

Now, finally, we need to write the form inside the gst-edit.component.html file.

<div class="card">
  <div class="card-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Person Name</label>
        <input type="text" class="form-control" formControlName="person_name" #person_name [(ngModel)] = "business.person_name" />
      </div>
      <div *ngIf="angForm.controls['person_name'].invalid && (angForm.controls['person_name'].dirty || angForm.controls['person_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['person_name'].errors.required">
          Person Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business Name </label>
        <input type="text" class="form-control" formControlName="business_name" #business_name [(ngModel)] = "business.business_name" />
      </div>
      <div *ngIf="angForm.controls['business_name'].invalid && (angForm.controls['business_name'].dirty || angForm.controls['business_name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_name'].errors.required">
          Person Business is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Business GST Number </label>
        <input type="text" class="form-control" formControlName="business_gst_number" #business_gst_number [(ngModel)] = "business.business_gst_number" />
      </div>
      <div *ngIf="angForm.controls['business_gst_number'].invalid && (angForm.controls['business_gst_number'].dirty || angForm.controls['business_gst_number'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['business_gst_number'].errors.required">
          Business GST Number is required.
        </div>
      </div>
      <div class="form-group">
        <button (click)="updateBusiness(person_name.value, business_name.value, business_gst_number.value)"
        [disabled]="angForm.invalid" 
        class="btn btn-primary">Update Business</button>
      </div>
    </form>
  </div>
</div>

Save the file and go to the listing page and click on the edit button and you will see the populated form from the database.

You can also see the warning like the following. Ignore for this demo tutorial.

forms.js:1193
It looks like you’re using ngModel on the same form field as formControlName.
Support for using the ngModel input property and ngModelChange event with
reactive form directives have been deprecated in Angular v6 and will be removed
in Angular v7.
Now, update the data. Inside the business.service.ts file, we need to write the function that updates the data.
// business.service.ts

updateBusiness(person_name, business_name, business_gst_number, id) {

    const obj = {
        person_name: person_name,
        business_name: business_name,
        business_gst_number: business_gst_number
      };
    this
      .http
      .post(`${this.uri}/update/${id}`, obj)
      .subscribe(res => console.log('Done'));
  }

Okay, now write the updateBusiness() function inside gst-edit.component.ts file.

// gst-edit.component.ts

updateBusiness(person_name, business_name, business_gst_number) {
   this.route.params.subscribe(params => {
      this.bs.updateBusiness(person_name, business_name, business_gst_number, params['id']);
      this.router.navigate(['business']);
});

Save the file, and you will be able to update the data.

#17: Delete the data.

So, if you find no error on the console, then you can successfully update the data.

 I have already written edit and update service to make an API calls. So till now, Create, Read, Update is complete of this Angular 7 CRUD Example Tutorial. Now, take a look at Delete.

Now, we need to define click event on the delete button inside the gst-get.component.html file.

<tr *ngFor="let business of businesses">
          <td>{{ business.person_name }}</td>
          <td>{{ business.business_name }}</td>
          <td>{{ business.business_gst_number }}</td>
          <td><a [routerLink]="['edit', business._id]" class="btn btn-primary">Edit</a></td>
          <td><a (click) = "deleteBusiness(business._id)" class="btn btn-danger">Delete</a></td>
</tr>

Now, write the deleteBusiness function inside the gst-get.component.ts file.

// gst-get.component.ts

deleteBusiness(id) {
    this.bs.deleteBusiness(id).subscribe(res => {
      console.log('Deleted');
    });
  }

Finally, create deleteBusiness() function inside the business.service.ts file.

// business.service.ts

deleteBusiness(id) {
    return this
              .http
              .get(`${this.uri}/delete/${id}`);
  }

Finally, Completed the delete functionality.

So, in this tutorial, we have complete the CRUD Functionality in Angular 7.

If you have any doubt in this Angular 7 CRUD Example, then ask in a comment below.

Github Code

The post Angular 7 CRUD Example | MEAN Stack Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/04/angular-7-crud-example-mean-stack-tutorial/feed/ 84
Node js File System Module Example Tutorial https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/ https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/#comments Tue, 09 Oct 2018 03:18:30 +0000 http://localhost/wordpress/?p=1887 node fs module file system example

Node js File System Module Example Tutorial is today’s leading topic.   The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file […]

The post Node js File System Module Example Tutorial appeared first on AppDividend.

]]>
node fs module file system example

Node js File System Module Example Tutorial is today’s leading topic.   The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file system operations have synchronous and asynchronous forms. The asynchronous form always takes the completion callback as its last argument. The arguments passed to a completion callback depend on a method, but the first argument is always reserved for the exception. If the operation was accomplished successfully, then the first argument will be null or undefined.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node js File System Module Example Tutorial

The everyday use for the File System module is as follows.

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

#Node.js as a File Server

We can require the fs module like the following code.

const fs = require('fs');

Let us take the example of simple file system operation in which we remove the file from disk.

Create one folder called filesystem and get inside that folder.

Now, create one file called acme.js inside the root for just demo purpose.

touch acme.js

We will delete this file using the fs module. So type the following code inside the server.js file.

// server.js

const fs = require('fs');

fs.unlink('acme.js', (err) => {
  if (err) throw err;
  console.log('File system operation successfully executed');
});

Now, run the following command in your terminal.

node server.js

It will give you the output like this and your file will be deleted from the project.

 

Node js File System Module Example Tutorial

#Using try-catch block

You can wrap the above operation in the try-catch block. Let us say we have already deleted the file and again we try to run the command then we will get the following error.

 

node fs module example

So, we need to define the try-catch error mechanism. Also for that, we need to perform the sync operation and not async operation.

// server.js

const fs = require('fs');

try {
    fs.unlinkSync('acme.js');
    console.log('File system operation successfully executed');
  }
catch(e) {
  console.log('Excecuted Catch block');
  console.log(e);
}

 

node filesystem example

So, we have used the fs module’s unlinkSync function.

#File paths

Most fs operations accept file paths that may be specified in the form of a string, a Buffer, or a URL object using the file protocol. String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by the process.cwd(). Recreate the acme.js file inside the root. Write the following code inside the server file.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial
// server.js

const fs = require('fs');

fs.open('acme.js', 'r', (err, fd) => {
  if (err) throw err;
  console.log('File has opened');
  fs.close(fd, (err) => {
    console.log('File is closing');
    if (err) throw err;
  });
});

#URL object support in node fs module

For most fs module functions, the path or filename argument may be passed as a WHATWG URL object. Only URL objects using the file protocol are supported.

// server.js

const fs = require('fs');
const fileUrl = new URL('file:///acme.js');

fs.readFileSync(fileUrl);

#Open a File using Node fs module

The syntax is following to open a file using node fs module.

fs.open(path, flags[, mode], callback)

Flags

Flags for reading/writing operations are the following.

Flag Description
r Open a file for reading. An exception occurs if a file does not exist.
r+ Open a file for reading and writing. An exception occurs if the file does not exist.
rs Open a file for reading in synchronous mode.
rs+ Open a file for reading and writing, asking the OS to open it synchronously. See notes for ‘rs’ about using this with caution.
w Open a file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like ‘w’ but fails if the path exists.
w+ Open a file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like ‘w+’ but fails if the path exists.
a Open a file for appending. The file is created if it does not exist.
ax Like ‘a’ but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like ‘a+’ but fails if the path exists.

Let us take an example of opening a file using the node fs module.

// server.js

const fs = require('fs');

fs.open('acme.js', 'r+', function(err, fd) {
  if (err) {
     return console.error(err);
  }
 console.log("File opened successfully!");     
});

You can run the file and see the output. If the file exists then, it will open in the mode of r+.

#Get File Information

Following is the syntax of the method to get the information about a  particular file. 

fs.stat(path, callback)

Let us take an example of node file stat.

// server.js

const fs = require('fs');

fs.stat('acme.js', function (err, stats) {
  if (err) {
      return console.error(err);
  }
  console.log(stats);
  console.log("Got file info successfully!");
  
  // Check file type
  console.log("isFile ? " + stats.isFile());
  console.log("isDirectory ? " + stats.isDirectory());    
});

Run and see the output in the terminal.

 

Get File Information in Node js

#Writing a File using Node fs module.

The syntax is following to write a file in node.js.

fs.writeFile(filename, data[, options], callback)

This method will overwrite the file if a file already exists. If you want to write into an existing file, then you should use another available method.

// server.js

const fs = require('fs');

fs.writeFile('acme.js', 'console.log("hello")', function (err) {
  if (err) throw err;
  console.log('New file acme.js is either created or if exists then updated');
});

#Reading a file using node fs module.

To read a file in node.js, you can use the following syntax.

fs.read(fd, buffer, offset, length, position, callback)

Let us take an example and understand how we can read the file using the node fs.

// server.js

const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('acme.js', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/js'});
    res.write(data);
    res.end();
  });
}).listen(8080);

The above code will spin up the http server and return the content of the file in the webpage. You can access the webpage at this URL: https://localhost:8080.

#Rename Files.

To rename a file with the File System module,  use the fs.rename() method. The fs.rename() method renames the specified file.

// server.js

const fs = require('fs');

fs.rename('acme.js', 'paradox.js', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

#Delete Files

To delete a file with the File System module,  use the fs.unlink() method. The fs.unlink() method deletes the specified file.

// server.js

const fs = require('fs');

fs.unlink('paradox.js', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

Run the file and the file will be removed from the disk.

Finally, Node js File System Module Example Tutorial is over. Thanks for taking.

The post Node js File System Module Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/feed/ 1
How To Save Multiple Checkboxes Values in React js https://appdividend.com/2018/09/25/how-to-save-multiple-checkboxes-values-in-react-js/ https://appdividend.com/2018/09/25/how-to-save-multiple-checkboxes-values-in-react-js/#respond Tue, 25 Sep 2018 21:20:04 +0000 http://localhost/wordpress/?p=1781 React js multiple checkbox example

In this tutorial, we will see How To Save Multiple Checkboxes Values in React js. If you are building a web application, then there are lots of form controls we need to create an interactive user form. The checkbox is one of the most used form control in a web application. We will take three checkboxes and […]

The post How To Save Multiple Checkboxes Values in React js appeared first on AppDividend.

]]>
React js multiple checkbox example

In this tutorial, we will see How To Save Multiple Checkboxes Values in React js. If you are building a web application, then there are lots of form controls we need to create an interactive user form. The checkbox is one of the most used form control in a web application. We will take three checkboxes and user can check multiple boxes and save its values inside MongoDB database. As we know, form control values are always controlled by React.js state. So when the user submits the form, we need only to send the values of checkboxes whose values are valid or whose checkbox values are checked. We save the values as a String in a MongoDB database. We use Node.js as a platform. There are many ways you can save multiple checkbox values in React js inside the MongoDB database.

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.
Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

How To Save Multiple Checkboxes Values in React

First of all, let us install React.js using the following command.

#1: Install React.js

npx create-react-app checkbox

Now, go inside the folder, and we need to install the bootstrap and axios libraries.

yarn add bootstrap axios

# or

npm install bootstrap axios --save

Next step is to import the bootstrap css file inside src >> App.js file.

// App.js

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

#2: Create Form inside an App.js.

For this example, I am merely taking the checkboxes and not other input types. So I am making three textboxes. So, first, we need to define the three initial state values.

// App.js

import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  state = {
    isMJ: false,
    isJB: false,
    isDrake: false
  };

  toggleChangeMJ = () => {
    this.setState(prevState => ({
      isMJ: !prevState.isMJ,
    }));
  }

  toggleChangeJB = () => {
    this.setState(prevState => ({
      isJB: !prevState.isJB,
    }));
  }

  toggleChangeDrake = () => {
    this.setState(prevState => ({
      isDrake: !prevState.isDrake,
    }));
  }

  onSubmit = (e) => {
    e.preventDefault();
    console.log(this.state);
  }

  render() {
    return (
      <div className="container">
        <h2>Save the multiple checkbox values in React js</h2>
        <hr />
        <form onSubmit = {this.onSubmit}>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isMJ}
                onChange={this.toggleChangeMJ}
                className="form-check-input"
              />
              MJ
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isJB}
                onChange={this.toggleChangeJB}
                className="form-check-input"
              />
              JB
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isDrake}
                onChange={this.toggleChangeDrake}
                className="form-check-input"
              />
              Drake
            </label>
          </div>
          <div className="form-group">
            <button className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

We have defined the three initial states. Each state is for one checkbox. 

We also need to handle the change event. So when the user either check the checkbox or uncheck the checkbox, the state will be changed. So when the user submits the form, we get all the three state, and if any of the checkboxes are checked, then we send it to the server and save the data in the MongoDB database.

#3: Convert checked values into String.

We will save the string into the database. The String is comma separated values. So, we filter the state, and if any of the checkbox value is right or true, we add into an array and then finally change that array into the string and send that data to the Node.js server.

So, write the following code inside onSubmit() function.

// App.js

onSubmit = (e) => {
    e.preventDefault();
    let arr = [];
    for (var key in this.state) {
      if(this.state[key] === true) {
        arr.push(key);
      }
    }
    let data = {
      check: arr.toString() 
    };
}

So, here as I have explained, the first loop through the states and if the value is true, we push into the new array and finally cast that array into the String.

#4: Use Axios to send a POST request.

Import the axios module and send the POST request to the node server. So our final App.js file looks like below.

// App.js

import React, { Component } from 'react';
import axios from 'axios';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  state = {
    isMJ: false,
    isJB: false,
    isDrake: false
  };

  toggleChangeMJ = () => {
    this.setState(prevState => ({
      isMJ: !prevState.isMJ,
    }));
  }

  toggleChangeJB = () => {
    this.setState(prevState => ({
      isJB: !prevState.isJB,
    }));
  }

  toggleChangeDrake = () => {
    this.setState(prevState => ({
      isDrake: !prevState.isDrake,
    }));
  }

  onSubmit = (e) => {
    e.preventDefault();
    let arr = [];
    for (var key in this.state) {
      if(this.state[key] === true) {
        arr.push(key);
      }
    }
    let data = {
      check: arr.toString() 
    };
    axios.post('http://localhost:4000/checks/add', data)
          .then(res => console.log(res.data));
  }

  render() {
    return (
      <div className="container">
        <h2>Save the multiple checkbox values in React js</h2>
        <hr />
        <form onSubmit = {this.onSubmit}>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isMJ}
                onChange={this.toggleChangeMJ}
                className="form-check-input"
              />
              MJ
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isJB}
                onChange={this.toggleChangeJB}
                className="form-check-input"
              />
              JB
            </label>
          </div>
          <div className="form-check">
            <label className="form-check-label">
              <input type="checkbox"
                checked={this.state.isDrake}
                onChange={this.toggleChangeDrake}
                className="form-check-input"
              />
              Drake
            </label>
          </div>
          <div className="form-group">
            <button className="btn btn-primary">
              Submit
            </button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

#5: Create a Node.js backend.

First, start the mongodb server using the following command.

mongodb

Now, create one folder inside the root of the checkbox – our react project folder called backend and go inside that folder and initialize the package.json file.

npm init -y

Now, install the following dependencies for node project.

yarn add express body-parser mongoose cors

# or

npm install express body-parser mongoose cors --save

Now, create a database connection using the following command.

// DB.js

module.exports = {
  DB: 'mongodb://localhost:27017/checks'
};

Now, create the routes and models folders inside the backend folder.

Inside the models folder, create one file CheckModel.js add the following code.

// CheckModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let CheckModel = new Schema({
  check: {
    type: String
  },
},{
    collection: 'checks'
});

module.exports = mongoose.model('CheckModel', CheckModel);

Also, you need to create the check.route.js file. Add the following code inside that file.

// CheckRoute.js

const checkRoute = require('express').Router(),
  CheckModel = require('../models/CheckModel');

  checkRoute.route('/add').post(function (req, res) {
    let checkmodel = new CheckModel(req.body);
    checkmodel.save()
      .then(Checkvalue => {
        res.status(200).json({'Checkvalue': 'Checkbox values have added successfully'});
      })
      .catch(err => {
        res.status(400).send("unable to save to database");
      });
  });

module.exports = checkRoute;

Finally, our server.js file looks like this.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB'),
  checkRoute = require('./routes/check.route');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.use('/checks', checkRoute);

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

Open the terminal inside the backend folder and hit the following command.

node server

So, now you have three servers are running.

  1. React Development Server
  2. Node server
  3. MongoDB server

Go to the browser and navigate to this URL: http://localhost:3000/

You can see this page.

How To Save Multiple Checkboxes Values in React js

 

Now, check the multiple boxes and submit the form. If everything goes correct, then you can see the response on your console.

Save multiple checkbox values in React

 

I have inserted multiple documents and you can see that inside the following image in the MongoDB database.

 

Multiple checkbox in React

Finally, our How To Save Multiple Checkboxes Values in React js Tutorial Example is over. Thanks for taking.

The post How To Save Multiple Checkboxes Values in React js appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/25/how-to-save-multiple-checkboxes-values-in-react-js/feed/ 0
React Datepicker Tutorial Example From Scratch https://appdividend.com/2018/09/24/react-datepicker-tutorial-example-from-scratch/ https://appdividend.com/2018/09/24/react-datepicker-tutorial-example-from-scratch/#comments Mon, 24 Sep 2018 09:33:51 +0000 http://localhost/wordpress/?p=1750 React Datepicker Demo Tutorial

React Datepicker Tutorial Example From Scratch is today’s leading topic.  We use the package called react-datepicker for this demo. React Date Picker is a  simple and reusable Datepicker component. There are many other packages available, but for this demo, we are using React Date Picker package for this example. If you want to learn more about React and Redux then check […]

The post React Datepicker Tutorial Example From Scratch appeared first on AppDividend.

]]>
React Datepicker Demo Tutorial

React Datepicker Tutorial Example From Scratch is today’s leading topic.  We use the package called react-datepicker for this demo. React Date Picker is a  simple and reusable Datepicker component. There are many other packages available, but for this demo, we are using React Date Picker package for this example.

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.
Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

React Datepicker Tutorial Example

Install React.js using the following command.

#1: Install React.js

Type the following command.

npx create-react-app reactdates
cd reactdates
npm start

 

React Datepicker Tutorial Example

#2: Install React Date Picker

Install react-datepicker using the following command.

npm install react-datepicker --save

# or

yarn add react-datepicker

We also need to install Moment.js separately since the dependency isn’t included in the package. Below is a simple example of how to use the Datepicker in a React view. You will also need to require the CSS file from this package.

npm install moment --save

# or

yarn add moment

Also, install the bootstrap using the following command.

npm install bootstrap --save

# or

yarn add bootstrap

Okay, now we have installed all the frontend libraries. Next step is to set up the frontend.

#3: Add Datepicker to the form

Inside src >> App.js file, replace the following code inside the App.js file.

// App.js

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
 
import 'react-datepicker/dist/react-datepicker.css';
import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      startDate: moment()
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    })
  }

  handleSubmit(e) {
    e.preventDefault();
    let main = this.state.startDate
    console.log(main.format('L'));
  }

  render() {
    return (
      <div className = "container">
        <h3>React Datepicker Example</h3>
        <form onSubmit={ this.handleSubmit }>
          <div className="form-group">
            <label>Select Date: </label>
            <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              name="startDate"
              dateFormat="MM/DD/YYYY"
            />
          </div>
          <div className="form-group">
            <button className="btn btn-success">Add Date</button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

#Explanation

Here, we have imported datpicker, moment, bootstrap libraries.

We have set the initial date to today’s date.

When the user changes the date, it will set the new state with its new values. 

When the user submits the date, we get the value of the textbox, which is the object of Moment so that we can call the moment function like formate on the value of the textbox. We can format the date in whatever way we want.

Now, <Datepicker /> component has many options that we can configure it.

The most basic use of the DatePicker can be described with:

<DatePicker selected={this.state.date} onChange={this.handleChange} />

You can use onSelect event handler which fires each time some calendar date has been selected.

<DatePicker selected={this.state.date}
  onSelect={this.handleSelect} //when day is clicked
  onChange={this.handleChange} //only when value has changed
/>

onClickOutside Handler may be useful to close datepicker in inline mode.

#Time picker

You can also include a time picker by adding the showTimeSelect prop.

<DatePicker
  selected={this.state.date}
  onChange={this.handleChange}
  showTimeSelect
  dateFormat="LLL" />

#4: Create the Node.js backend

Inside the root folder of reactdates, create one more folder called backend.

Go inside the folder and open the terminal and initialize the package.json file using the following command.

npm init -y

Now, install the following dependencies.

yarn add express body-parser mongoose cors

# or

npm install express body-parser mongoose --save

Also, install the nodemon as a development dependency.

npm install nodemon --save-dev

Now, create one file called the server.js and add the following code.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose');

  const PORT = process.env.PORT || 4000;

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

The next thing is to connect MongoDB database with our node.js application.

If you have not installed the MongoDB database then install it and then start the mongodb server.

Type the following command to start the MongoDB server.

mongod

React date example tutorial

So, Now, we need to connect our node.js application to the mongodb database.

Create one file called DB.js inside backend folder.

// DB.js

module.exports = {
  DB: 'mongodb://localhost:27017/reactdates'
};

Import this DB.js file inside our server.js file and use mongoose library to set up the database connection with MongoDB. We can also use Mongoose to save the data in the database using Mongoose ORM.

Write the following code inside the server.js file to connect our MongoDB application to the Node.js server.

// server.js

const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

Save a file and go to a terminal and start the node.js server using the following command. Make sure you are inside backend folder root and not in reactdates folder root.

nodemon server

 

MongoDB Date Tutorial

Now, We have the total of three servers are running.

  1. React Development Server.
  2. Node.js Server.
  3. Mongodb Server.

#5: Create a model and Express routes.

Now, we need to create two folders inside the backend folder called routes and models.

In the models’ folder, create one model called DateModel.js.

// DateModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let DateModel = new Schema({
  sDate: {
    type: Date
  },
},{
    collection: 'dates'
});

module.exports = mongoose.model('DateModel', DateModel);

Here, we will store only one field called sDate, and its datatype is Date.

In the routes folder, create one file called date.route.js. Add the following code inside the date.route.js file.

// date.route.js

const dateRoute = require('express').Router(),
      DateModel = require('../models/DateModel');

dateRoute.route('/add').post(function (req, res) {
  let datemodel = new DateModel(req.body);
  datemodel.save()
    .then(dateSaved => {
    res.status(200).json({'dateSaved': 'Date in added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

module.exports = dateRoute;

Now, our backend work is done. When the POST request hits the route: /dates/add, it will save the values inside the mongodb database.

Our final server.js file looks like this.

// server.js
const app = require('express')(),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose')
  config = require('./DB'),
  dateRoute = require('./routes/date.route');

  mongoose.Promise = global.Promise;
  mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
  );

  const PORT = process.env.PORT || 4000;

  app.use(bodyParser.json());
  app.use(cors());

  app.use('/dates', dateRoute);

  app.listen(PORT, () => {
    console.log('Listening on port ' + PORT);
  });

#6: Install Axios and send POST request.

Type the following command to install Axios library using the following command, and We need to install it on the frontend, so please open the terminal inside reactdates project root.

yarn add axios

# or

npm install axios --save

Okay, now import the axios inside App.js file and send the data to the Node.js server. Write the final code inside the App.js file.

// server.js

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import axios from 'axios';
 
import 'react-datepicker/dist/react-datepicker.css';
import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component {

  constructor (props) {
    super(props)
    this.state = {
      startDate: moment()
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    })
  }

  handleSubmit(e) {
    e.preventDefault();
    let mainDate = this.state.startDate;
    const dateObj = {
      sDate: mainDate.format('L')
    }
    axios.post('http://localhost:4000/dates/add', dateObj)
        .then(res => console.log(res.data));
  }

  render() {
    return (
      <div className = "container">
        <h3>React Datepicker Example</h3>
        <form onSubmit={ this.handleSubmit }>
          <div className="form-group">
            <label>Select Date: </label>
            <DatePicker
              selected={ this.state.startDate }
              onChange={ this.handleChange }
              name="startDate"
              dateFormat="MM/DD/YYYY"
            />
          </div>
          <div className="form-group">
            <button className="btn btn-success">Add Date</button>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

Save the file and go to the browser, select the data and submit the form and you can see in the console that, our date is successfully saved inside MongoDB database.

 

React Datepicker Tutorial

I have submitted four dates. So in the MongoDB database, there are four entries.

 

Mongoose Date Example Tutorial

Finally, React Datepicker Tutorial Example From Scratch is over. I have put the code on Github. Please check it out as well.

Github Code

The post React Datepicker Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/24/react-datepicker-tutorial-example-from-scratch/feed/ 1
Express Error Handling Example Tutorial https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/ https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/#comments Sun, 16 Sep 2018 08:22:43 +0000 http://localhost/wordpress/?p=1688 Express Route Handling Example Tutorial

Express Error Handling Example Tutorial is today’s leading topic. One of the most crucial things in a building web applications are error handling. The system will depend on many services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable, server timeout. So your consumers won’t be calling your endpoints with […]

The post Express Error Handling Example Tutorial appeared first on AppDividend.

]]>
Express Route Handling Example Tutorial

Express Error Handling Example Tutorial is today’s leading topic. One of the most crucial things in a building web applications are error handling. The system will depend on many services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable, server timeout. So your consumers won’t be calling your endpoints with the parameters you would expect. To prepare your application for such scenarios, you need to handle errors appropriately.

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express error handling middleware is a powerful tool for consolidating your HTTP error response logic.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Express Error Handling Example Tutorial

Let us take a simple example of error handling.

app.get('/customers', async function(req, res) {
  let customers;
  try {
    customers = await db.collection('Customer').find().toArray();
  } catch (error) {
    res.status(500).json({ error: error.toString() });
  }
  res.json({ customers });
});

Here, we have defined the endpoint called ‘/customers.’ So when any consumer tries to access the route ‘/customers,’ it will go through the try-catch block. If any error occurs then, it will immediately throw an exception and error will be returned otherwise the users will be returned.

The above pattern works well if you have one or two endpoints, but if you’re maintaining dozens of endpoints, then you are going to lose your mind quickly. Let’s say you have decided that HTTP response code 503 is more appropriate than HTTP 500; so you are going to have to change that for every single endpoint.

#Catching Express Errors

It is essential to assure that Express catches all the errors that occur while running route handlers and middleware. Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.

Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example:

app.get("/", function (req, res) {
  throw new Error("Opps!! Something went wrong"); // Express will catch this on its own.
});

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. For example:

app.get("/", function (req, res, next) {
  fs.readFile("/file-does-not-exist", function (err, data) {
    if (err) {
      next(err); // Pass errors to Express.
    }
    else {
      res.send(data);
    }
  });
});

#Writing error handling Middleware

Express middleware is divided into different types based on the number of arguments your middleware function takes. The middleware function that takes four arguments which are classified as “error handling middleware,” and will only get called if an error occurs. Define the error-handling middleware functions in the same way as other middleware functions are defined, except error-handling functions, have four arguments instead of three: (err, req, res, next). For example:

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

You define error-handling middleware last, after other app.use() and routes calls; for example:

const bodyParser = require('body-parser');
const methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

The only way to report errors to Express for use with error handlers is using the third argument to standard middleware, the next() function.

Now, let us take a practical example.

#1: Create Express Project

Create an express project folder.

mkdir errorexpress && cd errorexpress

Open the project in VSCode.

code .

Now, initialize the package.json file.

npm init -y

Install express using the following command.

npm install express --save

# or

yarn add express

#2: Setup Express server.

Okay, now inside the root,  create one file called server.js.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;


app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Now, add the exception code.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

app.get('*', function(req, res, next) {
  setImmediate(() => { 
    next(new Error('Ohh!! Something went wrong')); 
  });
});

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Save the file and go to the terminal and start the node server.

node server

 

Express Error Handling Example Tutorial

Now go to the browser and hit this URL: http://localhost:3000

You will see the JSON response with an error message. So this is how we can write a middleware that throws an error.

#Use With Async/Await in Error Middleware

Express was mostly written 2011-2014, before ES6, and it still lacks a good answer for how to handle the async/await keywords. We can write the above code in async/await manner.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Here, with a little helper function, you can tie async/await errors in with Express error handling middleware. Remember that async functions return promises, so you need to make sure to .catch() any errors and pass them to next():

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Finally, Express Error Handling Example Tutorial is over. Thanks for taking.

The post Express Error Handling Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/feed/ 3