express – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Mar 2019 08:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png express – 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/#respond 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/ 0
How To Serve Static Files in Express https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/ https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/#respond Sat, 24 Nov 2018 10:10:16 +0000 http://localhost/wordpress/?p=2312 Server static files in express

In this tutorial, we will see How To Serve Static Files in Express. Express is the Fast, unopinionated, minimalist web framework for Node.js. We can also build the robust api using HTTP utility methods and middleware at your disposal. Express provides the thin layer of web application features, without obscuring Node.js features that you know and love. Right now Express […]

The post How To Serve Static Files in Express appeared first on AppDividend.

]]>
Server static files in express

In this tutorial, we will see How To Serve Static Files in Express. Express is the Fast, unopinionated, minimalist web framework for Node.js. We can also build the robust api using HTTP utility methods and middleware at your disposal. Express provides the thin layer of web application features, without obscuring Node.js features that you know and love. Right now Express Framework’s version is 4.16.0.

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

How To Serve Static Files in Express

We can serve the static files such as images, CSS, and JavaScript files using the express.static built-in middleware function in Express. The syntax is following.

express.static(root, [options])

The root argument specifies a root directory from which to serve the static assets. The function determines the file to serve by combining the req.url with the provided a root directory. When the file is not found, instead of sending a 404 response, it instead calls next() to move on to a next middleware, allowing for stacking and fall-backs. Now, let us take an example to serve static files in express.

#1: Install Express and create a server

Create a project folder.

mkdir expstatic

Now, initialize the package.json file using the following command.

npm init -y

Install express using the following command.

npm install express --save

Now, create a folder inside the root called public.

Also, create one file inside the root called server.js.

// server.js

const express = require('express');

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

app.listen(PORT, () => {
  console.log('Server is running at:',PORT);
});
Go to the terminal and start the server.
node server

 

How To Serve Static Files in Express

#2: Add Static Middleware

First, we need to define the root directory that can act as a folder, from which we can load the static assets like CSS, JS, and Images.

In our case, it is the public directory. So let us define it.

// server.js

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

So, our server.js file looks like this.

// server.js

const express = require('express');

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

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

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

Now, our static files’ folder is loaded. Let us add the three files inside the public folder.

We have added three files inside the public folder.

// style.css

body {
  background-color: red
}
// app.js

function add(x)
{
  return x + x;
}
console.log(add(2));

And last one image.

Now, again restart the node server and go to the browser and type the following URLs.

  1. http://localhost:4000/style.css
  2. http://localhost:4000/app.js
  3. http://localhost:4000/Krunal.jpg

You can see the content inside the files in the browser. So, now we are serving the static files in express.

#Multiple Static Assets Directory

We can define the multiple static directories to serve the static files.

For that, we need to define the middleware two times.

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

In this case, you have two directories 1) public 2) files.

Express looks up the files in the order in which you set a static directory with a express.static middleware function.

To create the virtual path prefix (where the path does not exist in a file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below.

app.use('/content', express.static('public'))

So, here we have defined the prefix called /content.

So, when you access the path to the browser, you need to add the prefix like this.

  1. http://localhost:4000/content/Krunal.jpg
  2. http://localhost:4000/content/style.css
  3. http://localhost:4000/content/app.js

Finally, How To Serve Static Files in Express tutorial is over. Thanks for taking.

The post How To Serve Static Files in Express appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/feed/ 0
MEVN Stack Tutorial With Example From Scratch https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/ https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/#comments Wed, 21 Nov 2018 23:08:48 +0000 http://localhost/wordpress/?p=2278 MEVN Stack Tutorial Guide with Step by Step

MEVN Stack Tutorial With Example From Scratch is the topic, we will discuss today. We will generate FullStack Single Page Application(SPA) using MongoDB, Express, Vue, and Node.js CRUD Example Tutorial with step by step. For this example, we will not use Vuex for state management because this app will be simple and not complicated. We […]

The post MEVN Stack Tutorial With Example From Scratch appeared first on AppDividend.

]]>
MEVN Stack Tutorial Guide with Step by Step

MEVN Stack Tutorial With Example From Scratch is the topic, we will discuss today. We will generate FullStack Single Page Application(SPA) using MongoDB, Express, Vue, and Node.js CRUD Example Tutorial with step by step. For this example, we will not use Vuex for state management because this app will be simple and not complicated. We will create an application where the user can create, update, read, and delete the post. So, let us start the MEVN Stack Tutorial with an example.

If you want to learn more about Vue.js then check out this Vue JS 2 – The Complete Guide (incl. Vue Router & Vuex) course.

MEVN Stack Tutorial With Example From Scratch

We install Vue.js project using Vue CLI. Vue CLI requires the Node.js version 8.9 or above (8.11.0+ recommended). You can manage multiple versions of Node on the same machine with nvm or nvm-windows

Type the following command to install Vue CLI, if you have not installed.

npm install -g @vue/cli

# OR

yarn global add @vue/cli

You can check the version of Vue.js using this command.

vue --version

#1: Create a Vue.js project

Type the following command to install Vue.js.

vue create mevnexample

 

MEVN Stack Tutorial With Example From Scratch

Now, go inside the vue project.

cd mevnexample

Open the project inside code editor. I am using Visual Code.

code .

Start the vue dev server using the following command.

npm run serve

Go to the http://localhost:8080

You can see that we have successfully installed the Vue.js.

#2: Install Vue dependencies.

Type the following command to install the axiosvue-router and vue-axios dependencies. The vue-router is used for routing our Vue.js application to use the different components and the vue-axios for sending the network request to the server.

npm install axios vue-router vue-axios --save

Install the Bootstrap CSS Framework version 4 using the following command.

npm install bootstrap --save

Now, import the Bootstrap 4 CSS inside the main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

#3: Create the vue components.

Go to the src >> components folder and remove the HelloWorld.vue file and create the following components.

  1. HomeComponent.vue
  2. CreateComponent.vue
  3. EditComponent.vue
  4. IndexComponent.vue

Now, add the following code inside the HomeComponent.vue file.

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Home Component</div>

              <div class="card-body">
                  I'm the Home Component component.
              </div>
          </div>
      </div>
  </div>
</template>
<script>
export default {
}
</script>

Next step is to import the HomeComponent.vue file inside the App.vue file.

// App.vue

<template>
  <div>
    <HomeComponent />
  </div>
</template>

<script>
import HomeComponent from './components/HomeComponent.vue'

export default {
  name: 'app',
  components: {
    HomeComponent
  }
}
</script>

Save the file, and if the server is running, then you can go to the http://localhost:8080 and see that HomeComponent is rendering.

Now, create the remaining three components.

// CreateComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Create Component</div>

              <div class="card-body">
                  I'm the Create Component component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>
// EditComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Edit Component</div>

              <div class="card-body">
                  I'm an Edit component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>
// IndexComponent.vue

<template>
  <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card card-default">
              <div class="card-header">Index Component</div>

              <div class="card-body">
                  I'm an Index component.
              </div>
          </div>
      </div>
  </div>
</template>

<script>
  export default {
  }
</script>

#4: Configure the vue-router

Inside the main.js file, write the following code.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

import VueRouter from 'vue-router';
Vue.use(VueRouter);

Vue.config.productionTip = false;

import HomeComponent from './components/HomeComponent.vue';
import CreateComponent from './components/CreateComponent.vue';
import IndexComponent from './components/IndexComponent.vue';
import EditComponent from './components/EditComponent.vue';

const routes = [
  {
      name: 'home',
      path: '/',
      component: HomeComponent
  },
  {
      name: 'create',
      path: '/create',
      component: CreateComponent
  },
  {
      name: 'posts',
      path: '/posts',
      component: IndexComponent
  },
  {
      name: 'edit',
      path: '/edit/:id',
      component: EditComponent
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(Vue.util.extend({ router }, App)).$mount('#app');

What we have done is that, first, imported the vue-router module and then create an array of routes which has a name, path, and components as the properties.

Then we have created the router object and passed the mode history and the routes array. So when the application boot, we will give these routes to the vue application.

Now, the next step is to define the <router-view></router-view> element. It renders the component according to the routing path in the Vue application.

So, add the <router-view> inside the App.vue file.

// App.vue

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script>


export default {
  name: 'app'
}
</script>

Save the file and check the following route paths to see if we are getting the exact routes.

  1. http://localhost:8080/create
  2. http://localhost:8080/posts
  3. http://localhost:8080/edit/21

#5: Create a Navigation bar

Write the following code inside the App.vue file. I have added the navbar.

// App.vue

<template>
  <div class="container">
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <ul class="navbar-nav">
        <li class="nav-item">
          <router-link to="/" class="nav-link">Home</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/create" class="nav-link">Create Post</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/posts" class="nav-link">Posts</router-link>
        </li>
      </ul>
    </nav><br />
    <transition name="fade">
      <router-view></router-view>
    </transition>
  </div>
</template>

<style>
    .fade-enter-active, .fade-leave-active {
      transition: opacity .5s
    }
    .fade-enter, .fade-leave-active {
      opacity: 0
    }
</style>

<script>

    export default{
    }
</script>

So, what we have done is that add the navigation bar and add some animation effect like transition. So when we navigate the routes, the component is changing according to their path.

 

Vue Node CRUD Example

#6: Create a Form

We need to create a form to enter the details of form. So let us create a form inside the CreateComponent.vue file.

// CreateComponent.vue

<template>
  <div>
    <h1>Create A Post</h1>
    <form @submit.prevent="addPost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Create</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {
        data(){
        return {
          post:{}
        }
    },
    methods: {
      addPost(){
        console.log(this.post);
      }
    }
  }
</script>

Also, we have defined the object called post. So here, we have used the two-way data binding. The post object has two properties. 1) title 2) body.

We have made one method called addPost().  So, when a user submits the form, we will get the input inside the addPost() method. From then, we will send a POST request to the Laravel server and to save the data into the database.

I am skipping the validation of each field because this article is getting long and long. So we will do it in another post.

Save the file and go to this URL: http://localhost:8080/create or /create. You can see the form like below.

 

Vue Express CRUD Tutorial Example

#7: Create a Node.js backend.

Create one folder inside the vue project root called api and go inside that folder.

Now, 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 a nodemon server as a development dependency. So that we do not need to restart every time, we change our server code.

We have installed the express web framework which is built on top of the Node.js server. Also, installed the body-parser module to parse the data coming from the request and then installed the cors module which will help us to ignore the cross-site request origin warning from the browser. It is security provided by the browser when we request them from a different server.

npm install nodemon --save-dev

Now create three files called server.js, DB.js, post.model.js, and post.route.js. All these files are inside the root of the api folder. Write the following code in 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');

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

Now, we need to start a node server using the following command.

nodemon server

So, our node.js server is running at port: 4000

 

Vue Node Tutorial Example

#8: Setup and connect MongoDB database.

If you are the beginner in the MongoDB database, then please check out my 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. You can also use any MongoDB, database client. I am just using the terminal for this demo because it is a simple application.

mongod

Inside an api folder, create one file called the DB.js which is responsible for connecting our node application to the mongodb database. So add the following line of code.

// DB.js

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

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

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 the mongodb database.

#9: Create a Mongoose Schema

Write the following code inside the post.model.js file.

// post.model.js

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

// Define collection and schema for Post
let Post = new Schema({
  title: {
    type: String
  },
  body: {
    type: String
  }
},{
    collection: 'posts'
});

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

We have taken three fields called title and body with String datatype.

#10: Define a route for Node.js Express application

Write the CRUD operation code inside the post.route.js file.

// post.model.js

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

// Require Post model in our routes module
let Post = require('./post.model');

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

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

// Defined edit route
postRoutes.route('/edit/:id').get(function (req, res) {
  let id = req.params.id;
  Post.findById(id, function (err, post){
      if(err) {
        res.json(err);
      }
      res.json(post);
  });
});

//  Defined update route
postRoutes.route('/update/:id').post(function (req, res) {
    Post.findById(req.params.id, function(err, post) {
    if (!post)
      res.status(404).send("data is not found");
    else {
        post.title = req.body.title;
        post.body = req.body.body;
        post.save().then(() => {
          res.json('Update complete');
      })
      .catch(() => {
            res.status(400).send("unable to update the database");
      });
    }
  });
});

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

module.exports = postRoutes;

Here, we have defined the CRUD operations in Node.js, which is backend server side. So when the request from the clientside hits the node express 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, and in our case, it is vue.js frontend.

Here, we have used a Mongoose ORM to create, read, update, delete the data from the mongodb databaseMongoose is an ORM(Object Relational Mapping) used in the MongoDB database. Now, we have all the CRUD operations set up on the post.route.js 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 postRoute = require('./post.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('/posts', postRoute);

app.listen(PORT, function(){
  console.log('Server is running on Port:',PORT);
});
If the linter is showing error on console statement inside the Visual Studio Code editor or other editors, then ignore it because it is warning provided by eslint configuration. It is not an actual error and you can able to see the output inside the browser.

#11: Use axios to send a network request

Go to the frontend vue project and import the axios and vue-axios inside the main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'

import VueRouter from 'vue-router';
Vue.use(VueRouter);

import VueAxios from 'vue-axios';
import axios from 'axios';

Vue.use(VueAxios, axios);

Vue.config.productionTip = false;

import HomeComponent from './components/HomeComponent.vue';
import CreateComponent from './components/CreateComponent.vue';
import IndexComponent from './components/IndexComponent.vue';
import EditComponent from './components/EditComponent.vue';

const routes = [
  {
      name: 'home',
      path: '/',
      component: HomeComponent
  },
  {
      name: 'create',
      path: '/create',
      component: CreateComponent
  },
  {
      name: 'posts',
      path: '/posts',
      component: IndexComponent
  },
  {
      name: 'edit',
      path: '/edit/:id',
      component: EditComponent
  }
];

const router = new VueRouter({ mode: 'history', routes: routes});

new Vue(Vue.util.extend({ router }, App)).$mount('#app');

Now, we have created the backend. Next step is to send the POST request to the node.js api server. Remember, now we have now three servers are running.

  1. Vue development server
  2. Node.js server
  3. MongoDB server

Remember, all are running fine otherwise the project won’t work.

Write the following code inside the CreateComponent.vue file’s addPost() function.

// CreateComponent.vue

addPost(){
    let uri = 'http://localhost:4000/posts/add';
    this.axios.post(uri, this.post).then(() => {
       this.$router.push({name: 'posts'});
    });
}

You can now create the post and see in the mongodb database.

To check from the terminal, you need to open the mongoshell using the following command.

mongo

 

MongoDB database example

#12: Display the backend data

Write the following code inside the IndexComponent.js file.

// IndexComponent.js

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
              <th>Title</th>
              <th>Body</th>
              <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post._id">
                  <td>{{ post.title }}</td>
                  <td>{{ post.body }}</td>
                  <td><router-link :to="{name: 'edit', params: { id: post._id }}" class="btn btn-primary">Edit</router-link></td>
                  <td><button class="btn btn-danger">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://localhost:4000/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data;
      });
    }
  }
</script>

When the component is created, it will send a GET request to the node.js server and fetch the data from the database and then assign that data to the posts array, and then we loop through that array and display the data in the tabular format.

MEVN CRUD Example

 

#13: Send edit and update request

Now, when our edit component loads, we need to fetch the data from the server to display the existing data.

Then, after changing the data in the textbox and textarea, we hit the update button, and we call the updatePost() function to send a post request to the server to update the data.

// EditComponent.vue

<template>
  <div>
    <h1>Edit Post</h1>
    <form @submit.prevent="updatePost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title">
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Post Body:</label>
              <textarea class="form-control" v-model="post.body" rows="5"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Update</button>
        </div>
    </form>
  </div>
</template>

<script>
    export default {

      data() {
        return {
          post: {}
        }
      },
      created() {
        let uri = `http://localhost:4000/posts/edit/${this.$route.params.id}`;
        this.axios.get(uri).then((response) => {
            this.post = response.data;
        });
      },
      methods: {
        updatePost() {
          let uri = `http://localhost:4000/posts/update/${this.$route.params.id}`;
          this.axios.post(uri, this.post).then(() => {
            this.$router.push({name: 'posts'});
          });
        }
      }
    }
</script>

You will see the edit data from the database and also you can update the database. So till now, insert, read,  and update operations are complete. Now, last, the delete is remaining.

#14: Delete or Remove the data.

Now, the only remaining thing is to delete or remove the data from the database.

So, let us write the final code inside the IndexComponent.vue file.

// IndexComponent.vue

<template>
  <div>
      <h1>Posts</h1>
        <div class="row">
          <div class="col-md-10"></div>
          <div class="col-md-2">
            <router-link :to="{ name: 'create' }" class="btn btn-primary">Create Post</router-link>
          </div>
        </div><br />

        <table class="table table-hover">
            <thead>
            <tr>
              <th>Title</th>
              <th>Body</th>
              <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="post in posts" :key="post._id">
                  <td>{{ post.title }}</td>
                  <td>{{ post.body }}</td>
                  <td><router-link :to="{name: 'edit', params: { id: post._id }}" class="btn btn-primary">Edit</router-link></td>
                  <td><button class="btn btn-danger" @click.prevent="deletePost(post._id)">Delete</button></td>
                </tr>
            </tbody>
        </table>
  </div>
</template>

<script>
  export default {
      data() {
        return {
          posts: []
        }
      },
      created() {
      let uri = 'http://localhost:4000/posts';
      this.axios.get(uri).then(response => {
        this.posts = response.data;
      });
    },
    methods: {
      deletePost(id)
      {
        let uri = `http://localhost:4000/posts/delete/${id}`;
        this.axios.delete(uri).then(response => {
          this.posts.splice(this.posts.indexOf(id), 1);
        });
      }
    }
  }
</script>

Save the file, and now, you can also delete the values from the MongoDB database.

So, finally, our MEVN Stack Tutorial With Example Demo is over. I have put this code on Github. So check that out as well.

Github Code

Steps to use code

  1. Clone the repository.
  2. Go inside the vue project and type this command: npm install
  3. Go inside the api folder and type this command: npm install
  4. Now, start the mongodb server.
  5. Also, start the node server using this command: nodemon server
  6. Go to the vue root project and type this command: npm run serve
  7. Go to the http://localhost:8080 and your project is running.

The post MEVN Stack Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/21/mevn-stack-tutorial-with-example-from-scratch/feed/ 6
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/ 34
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/ 1
How To Create Express HTTPS Server With A Self-Signed Certificate https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/ https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/#respond Mon, 10 Sep 2018 12:23:14 +0000 http://localhost/wordpress/?p=1636 Create Express HTTPs Server in Nodejs

How To Create Express HTTPS Server With A Self-Signed Certificate is today’s leading topic. If we need start our node.js server on node.js then to be able to serve a site on HTTPS from localhost you need to create a self-signed certificate. The self-signed certificate will be enough to establish a secure HTTPS connection, although browsers […]

The post How To Create Express HTTPS Server With A Self-Signed Certificate appeared first on AppDividend.

]]>
Create Express HTTPs Server in Nodejs

How To Create Express HTTPS Server With A Self-Signed Certificate is today’s leading topic. If we need start our node.js server on node.js then to be able to serve a site on HTTPS from localhost you need to create a self-signed certificate. The self-signed certificate will be enough to establish a secure HTTPS connection, although browsers will complain that the certificate is self-signed and as such it’s not trusted. It is still great for development purposes. Let us say, if you are working with React Native or other iOS development then you need an API point, and if the API point is served via HTTPs then it will be straightforward otherwise it gets complicated to get the response from the server. I have found very painful while developing frontend and backend apps. So it can be beneficial in these scenarios.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)
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

Create Express HTTPS Server With A Self-Signed Certificate

Okay, first you must have installed the OpenSSL installed on your machine. If not, on a Mac you can install it using brew install OpenSSL if you use Homebrew. Otherwise, search on Google “how to install openssl on ”.

If you want to upgrade your current OpenSSL version, then update the OpenSSL using the following command.

brew upgrade openssl

Once an OpenSSL is installed, hit this command.

openssl req -nodes -new -x509 -keyout server.key -out server.cert

You will prompt for some answers. Give the answers one by one.

 

Create Express HTTPS Server With A Self-Signed Certificate

That’s it! Now you have two files in the folder where you ran the following command.

  • server.cert is the self-signed certificate file.
  • server.key is the private key of the certificate.

Both files will be needed to establish the HTTPS connection, and depending on how you are going to set up your server, the process to use them will be different.

Those files need to be put in place reachable by the application; then you need to configure the server to use them.

This is an example using the https core module and Express.

// server.js

const https = require('https')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({}, app).listen(3000, () => {
  console.log('Listening...')
})

Now initialize the package.json file using the following command.

npm init -y

Okay, now install the express using the following command.

npm install express --save

Okay, finally our code with the certificates is the following.

// server.js

const https = require('https');
const express = require('express');
const fs = require('fs');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(3000, () => {
  console.log('Listening...')
});

Save the file and go to the terminal.

node server

Go to the browser and hit this URL: https://localhost:3000.

At first, it will say, it is insecure because it is self-signed but ignores this error, and now you can access the content. The looking is not great on the browser because it will say insecure but trust me for a local developing purpose; it is excellent.

Finally, How To Create Express HTTPS Server With A Self-Signed Certificate tutorial is over. Thanks for taking.

The post How To Create Express HTTPS Server With A Self-Signed Certificate appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/feed/ 0
Express Post Request Example Tutorial https://appdividend.com/2018/08/22/express-post-request-example-tutorial/ https://appdividend.com/2018/08/22/express-post-request-example-tutorial/#comments Wed, 22 Aug 2018 14:04:26 +0000 http://localhost/wordpress/?p=1525 Node Express body-parser post request example tutorial

Express Post Request Example Tutorial is today’s leading topic. When we use Node.js as a platform, then we almost use expressjs as our web framework. So when we are building applications using ExpressJS, we will need to get information from our users. In the HTTP sense, we have two main ways to collect the data from the user via […]

The post Express Post Request Example Tutorial appeared first on AppDividend.

]]>
Node Express body-parser post request example tutorial

Express Post Request Example Tutorial is today’s leading topic. When we use Node.js as a platform, then we almost use expressjs as our web framework. So when we are building applications using ExpressJS, we will need to get information from our users. In the HTTP sense, we have two main ways to collect the data from the user via browser and that is GET and POST. In this example, we use the POST method to obtain the information from the User. So when a user sends a request from the client, we receive the request and extract the data from the request and save the data into the database.

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

Express Post Request Example Tutorial

We start our demo by installing expressjs. But before that let us create a project folder by the following command.

mkdir expresspost

Go into the project folder.

cd expresspost

Open the project inside VSCode.

code .

#1: Install Expressjs.

Initialize the package.json file using the following command.

npm init

You can install express using NPM or Yarn. It does not matter here.

yarn add express

# or

npm install express --save

Also, install nodemon server as a development dependency.

npm install nodemon --save-dev

# or

yarn add nodemon --dev

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

// server.js

const express = require('express');

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

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

Go to the terminal and hit the following command to start the nodemon server.

nodemon server

 

Express Post Request Example Tutorial

#2: Connect Express app to MongoDB database.

First, start the MongoDB server using the following command. Please install the MongoDB, if you have not installed previously.

mongod

Now, inside the root of the project folder, create one file called db.js and add the following code in it.

// db.js

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

Okay, now install the Mongoose library using the following command.

yarn add mongoose

# or

npm install mongoose --save

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 mongoose = require('mongoose');

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

const config = require('./db');

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

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

Here, we have connected our node express app to the MongoDB database.

#3: Install body-parser module.

We need to install body-parser module because to handle the HTTP POST request in Express.js version 4 and above; you need to install middleware module called body-parser. The body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

yarn add body-parser

# or

npm install body-parser --save

The body-parser parses the HTTP request body. It usually is necessary when you need to know more than just the URL you send to the server, particular in the context of a POST or PUT  or PATCH HTTP request where the information you want is contained in the body.

Primarily it is a middleware for parsing the JSON data, plain text as you require.

After adding the body-parser, our server.js file looks like this.

// server.js

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

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

const config = require('./db');

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

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

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

 #4: Create a Mongoose Model.

Inside the root, create one file called User.js and add the following schema in it.

// User.js

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

const User = new Schema({
  name: {
    type: String
  },
  email: {
      type: String
  }
},{
    collection: 'users'
});

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

So, here we have defined our schema for the users’ collection. It contains two fields.

  1. name
  2. email

#5: Create Express routes for the application.

Inside the root folder, create one file called UserRoute.js and add the following code.

// UserRouter.js

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

const User = require('./User');

UserRouter.route('/create').post(function (req, res) {
  const user = new User(req.body);
  user.save()
    .then(user => {
      res.json('User added successfully');
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});

module.exports = UserRouter;

Here, we have used the POST request to store the data inside MongoDB database. We have already installed and configured the body-parser middleware, so we can extract the data that can be used and save into the database.

Now, import this file inside the server.js.

// server.js

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

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

const config = require('./db');
const UserRoute = require('./UserRoute');

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

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

app.use('/user', UserRoute);

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

#6: Send A Post Request From POSTMAN.

Okay, now we need to send a request to a Node server. Make sure you have running the Node.js server. If not then you can start it by the following command.

nodemon server

Now, if you send an express post request to the server, then it returns the following json. Remember, you need to add form data which is name and email. Here, you need to select the x-www-form-urlencoded so that you can get the data into the req.body.

Express POST Body Example | body-parser tutorial with example

 

Now, check the MongoDB database.

 

express body-parser tutorial with example

So, here, we have successfully saved the data using express post request example.

We can see the request by logging in the console. Just put the console.log statement inside the UserRoute.js file.

// UserRoute.js

UserRouter.route('/create').post(function (req, res) {
  const user = new User(req.body);
  console.log(user);
  user.save()
    .then(user => {
      res.json('User added successfully');
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});

 

node express post example tutorial

Finally, Express Post Request Example is over. Thanks for taking.

The post Express Post Request Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/22/express-post-request-example-tutorial/feed/ 1
How To Setup Node Express and MongoDB in Docker https://appdividend.com/2018/04/13/how-to-setup-node-express-and-mongodb-in-docker/ https://appdividend.com/2018/04/13/how-to-setup-node-express-and-mongodb-in-docker/#comments Fri, 13 Apr 2018 22:30:22 +0000 http://localhost/wordpress/?p=432 How To Setup Node Express and MongoDB in Docker

In this tutorial, we will see How To Setup Node Express and MongoDB in Docker from scratch. Docker has become a standard tool not only among DevOps and Infrastructure people but also for the daily work of any developer. This article is aimed at the Docker beginners, who want to get a fully working instance of a Node […]

The post How To Setup Node Express and MongoDB in Docker appeared first on AppDividend.

]]>
How To Setup Node Express and MongoDB in Docker

In this tutorial, we will see How To Setup Node Express and MongoDB in Docker from scratch. Docker has become a standard tool not only among DevOps and Infrastructure people but also for the daily work of any developer. This article is aimed at the Docker beginners, who want to get a fully working instance of a Node Express and MongoDB app up and running in a matter of seconds for daily work. Docker will help you spin up containers (which behave like Virtual Machines but are not that heavy) and run your app on it. It gives us the ability to port the container anywhere we want on any server we want, moving from local to production gets secure and less buggy as the environment of the container which is running the app does not change.

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

Setup Node Express and MongoDB in Docker

We will start this tutorial by creating simple Node Express application. So let us do it.

Step 1: Install the dependencies.

Create a project folder in your main directory by the following command.

mkdir newdock

Go into the folder.

cd newdock

Install the following dependencies.

yarn add express mongodb

or

npm install express mongodb --save

I am using Yarn package manager, you can also use npm.

Step 2: Create server.js file.

First, we need to create one database file that returns the database string. So create one file db.js inside the root.

// db.js

module.exports = {
    DB: 'mongodb://mongo:27017/newdock'
}

Notice that, I have not written the localhost in the connection string. That is because we are connecting our Express application to the mongodb container. You will see later in this article.

Write the following primary express application inside a server.js file.

// server.js

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

const config = require('./db');
const PORT = 4000;
const client = mongodb.MongoClient;

client.connect(config.DB, function(err, db) {
    if(err) {
        console.log('database is not connected')
    }
    else {
        console.log('connected!!')
    }
});

app.get('/', function(req, res) {
    res.json({"hello": "world"});
});

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

I have created an express instance and also connect our application to the database.

Our Node application serves at Port: 4000 and when we hit the root URL(‘/’) than in response, we get the JSON data.

We have installed mongodb package that can help us to connect our app to mongodb database.

Now, our application is ready. The next step is to write the Dockerfile and docker-compose.yml file.

Step 3: Write Dockerfile inside root folder.

Inside the root folder, create a file called Dockerfile.

FROM node:7
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
CMD node server.js
EXPOSE 4000

What it does is, we will create one container called an app and that in that container, our whole project dependencies have resided. So when we deploy our container to the server, it will first install all the dependencies and then spin up the node server. The application will run on port 4000.

Step 4: Write the docker-compose.yml file.

Inside the root folder, create one file called docker-compose.yml file. Copy the following code.

version: "2"
services:
  app:
    container_name: app
    restart: always
    build: .
    ports:
      - "4000:4000"
    links:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - "27017:27017"

Here, we are building two containers.

  1. app container(It is our express app)
  2. mongodb container(mongodb server).

Step 5: Build the Docker containers.

If you have not installed the Docker, then please install it using this link.

Now, open the terminal in the root of the project and type the following command.

docker-compose build

It will create the containers and put our whole code inside it. It will generate step by step. Install all the dependencies and last successfully form the containers. Now, our containers are built successfully; we need to run the container.

Step 6: Run the containers.

We can up our containers using the following command.

docker-compose up

If everything is fine, you can see something like this.

Setup Node Express and MongoDB in Docker

 

Our app is running on port 4000 and we have successfully connected to the mongodb database.

Now, remember, when you need to change the file, you need to rebuild the container, and then you run. Otherwise, your latest changes will not reflect on the container.

Go to the browser and hit this URL: http://localhost:4000/

You can see that we are getting the JSON response. We have also connected our express application to the mongodb database.

Code on Github

Finally, our How To Setup Node Express and MongoDB in Docker Tutorial is over. Thanks for taking.

The post How To Setup Node Express and MongoDB in Docker appeared first on AppDividend.

]]>
https://appdividend.com/2018/04/13/how-to-setup-node-express-and-mongodb-in-docker/feed/ 6
React Express Tutorial Example From Scratch https://appdividend.com/2018/04/05/react-express-tutorial-example/ https://appdividend.com/2018/04/05/react-express-tutorial-example/#comments Thu, 05 Apr 2018 12:25:11 +0000 http://localhost:8888/wordpress/?p=318 React Express Tutorial Example From Scratch

React Express Tutorial Example From Scratch is the leading topic. For this example, we will use React js as a frontend library, node.js as a backend server platform and MongoDB as a database to store the data. React Express Tutorial will help you to setup both Express and React js environment to your local machine. If […]

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

]]>
React Express Tutorial Example From Scratch

React Express Tutorial Example From Scratch is the leading topic. For this example, we will use React js as a frontend library, node.js as a backend server platform and MongoDB as a database to store the data. React Express Tutorial will help you to setup both Express and React js environment to your local machine.

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

React Express Tutorial

We start our tutorial by installing the React js on our machine.

Step 1: Install React using create react app.

Go to your project drive and hit the following command.

npx create-react-app react-express-tutorial

Okay, after installing, go into that directory.

cd react-express-tutorial

Start the development server.

yarn start

Step 2: Define the routing of components.

Type the following command in your terminal to install react- router-dom module.

yarn add react-router-dom

It will install the dependency. If you are getting an error, then please install the Yarn, the package manager. Now, open the code in your favorite editor. I am using Visual Studio Code.

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

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';

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

Create three components.

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

  1. CreateComponent.js
  2. EditComponent.js
  3. IndexComponent.js
// CreateComponent.js

import React, { Component } from 'react';

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

import React, { Component } from 'react';

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

import React, { Component } from 'react';

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

Now, define the routes for each component.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

import CreateComponent from './components/CreateComponent';
import EditComponent from './components/EditComponent';
import IndexComponent from './components/IndexComponent';

class App extends Component {
  render() {
    return (
    <Router>
        <div>
          <h2>Welcome to React Express Tutorial</h2>
          <ul>
          <li><Link to={'/'}>Home</Link></li>
            <li><Link to={'/create'}>Create</Link></li>
            <li><Link to={'/index'}>List</Link></li>
            <li><Link to={'/edit/:id'}>Edit</Link></li>
          </ul>
          <hr />
          <Switch>
              <Route exact path='/create' component={CreateComponent} />
              <Route path='/edit/:id' component={EditComponent} />
              <Route path='/index' component={IndexComponent} />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Finally, save the file and go to the http://localhost:3000/

Step 3: Include Bootstrap 4 and create a form.

Install Bootstrap 4 using the following command.

yarn add bootstrap@4.0.0

After that, go to the index.js file and import the bootstrap as an NPM dependency.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';

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

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

Now, if your development server is running, then you can see the bootstrap styles applied to the React Express Application. Give the style to navigation. For that our code looks like below.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';

import CreateComponent from './components/CreateComponent';
import EditComponent from './components/EditComponent';
import IndexComponent from './components/IndexComponent';

class App extends Component {
  render() {
    return (
    <Router>
        <div className="container">
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <a className="navbar-brand">React Express App</a>
            <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>
                <li className="nav-item">
                  <Link to={'/edit/:id'} className="nav-link">Edit</Link>
                </li>
              </ul>
            </div>
          </nav>
          <Switch>
              <Route exact path='/create' component={CreateComponent} />
              <Route path='/edit/:id' component={EditComponent} />
              <Route path='/index' component={IndexComponent} />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Apply marignTop: 50 property to all the three components.

// CreateComponent.js

import React, { Component } from 'react';

export default class CreateComponent extends Component {
    render() {
        return (
            <div style={{marginTop: 50}}>
                <p>Welcome to Create Component!!</p>
            </div>
        )
    }
}

Okay, now you can see our design is completely changed.

 

React Express MongoDB Tutorial

Create a Bootstrap Form

Write the code to generate the bootstrap form inside CreateComponent.js file.

// CreateComponent.js

import React, { Component } from 'react';

export default class CreateComponent extends Component {
    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

 

create node server

Step 4: Submit the Form.

Okay, now we have two fields.

  1. server name
  2. server port

So we need to create three functions that can track both the values and set the state according to it. Also, the third function will send the POST request to the node express server.

// CreateComponent.js

import React, { Component } from 'react';

export default class CreateComponent extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            port: ''
        }
    }
    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        console.log(`name is ${this.state.name} and port is ${this.state.port}`);
        this.setState({
            name: '',
            port: ''
        })
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" value={this.state.name} className="form-control" onChange={this.onChangeHostName}/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" value={this.state.port} className="form-control" onChange={this.onChangePort}/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

So, when you submit the form, you can see here, that we can get both the textbox’s value in the console. Now, that values will be sent to the Node.js server and save into the database.

Step 5: Create a Node.js server and install Express Framework.

Okay, let us take a break from front end part and go to the backend part of our application. Inside our project root, create one folder called server. Inside server folder, create one file called server.js. Now, install the express as well as other dependencies.

yarn add express nodemon body-parser cors mongoose
// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4200;
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);
});

I have imported all the required packages inside a server.js file.

Okay, now start the Node.js server using the following command.

nodemon server/server

The first server is the folder name and the second server is a server.js file.

You can see in the terminal that, Node js server is running at PORT: 4200.

Step 6: Setup the 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

Also, I need to start the Mongo Shell to interact with the database. So in another tab of the terminal, type the following command open Mongo Shell.

mongo

Step 7: Connect Express App to Mongo Database.

Inside server folder, create one folder called database. Inside database folder, create one file called DB.js.

// DB.js

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

In my local database, my 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 mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4200;
const cors = require('cors');
const config = require('./database/DB');

mongoose.connect(config.DB).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 see the terminal, you can see that, our database is connected with our Express application.

Step 8: Create a Mongoose schema.

Create one folder inside server folder called models. Inside the models foldercreate one file called ServerPort.js.

// ServerPort.js

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

// Define collection and schema for Items
var ServerPort = new Schema({
  name: {
    type: String
  },
  port: {
      type: Number
  }
},{
    collection: 'servers'
});

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

Step 9: Create Express routes for the application.

Inside server folder, create one folder called routes. Inside that routes folder, create one file called ServerPortRouter.js

// ServerPortRouter.js

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

const ServerPort = require('../models/ServerPort');

ServerPortRouter.route('/add').post(function (req, res) {
  const serverport = new ServerPort(req.body);
  serverport.save()
    .then(serverport => {
        res.json('Server added successfully');
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

ServerPortRouter.route('/').get(function (req, res) {
    ServerPort.find(function (err, serverports){
    if(err){
      console.log(err);
    }
    else {
      res.json(serverports);
    }
  });
});

ServerPortRouter.route('/edit/:id').get(function (req, res) {
  const id = req.params.id;
  ServerPort.findById(id, function (err, serverport){
      res.json(serverport);
  });
});

ServerPortRouter.route('/update/:id').post(function (req, res) {
    ServerPort.findById(req.params.id, function(err, serverport) {
    if (!serverport)
      return next(new Error('Could not load Document'));
    else {
      // do your updates here
      serverport.name = req.body.name;
      serverport.port = req.body.port;

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

ServerPortRouter.route('/delete/:id').get(function (req, res) {
    ServerPort.findByIdAndRemove({_id: req.params.id},
       function(err, serverport){
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = ServerPortRouter;

The last step is to import this ServerPortRouter.js file into the server.js file.  So the final server.js file looks like below.

// server.js

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

const config = require('./database/DB');
const ServerPortRouter = require('./routes/ServerPortRoutes');

mongoose.connect(config.DB).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('/serverport', ServerPortRouter);

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

Step 10: Install Axios library and send the POST request to the server.

We are using Axios library for the network request to the Node.js server. So let’s install it first.

yarn add axios

Now, send the post request along with the form data to the node js server.

// CreateComponent.js

onSubmit(e) {
        e.preventDefault();
        const serverport = {
            name: this.state.name,
            port: this.state.port
        }
        axios.post('http://localhost:4200/serverport/add', serverport)
        .then(res => console.log(res.data));
        this.setState({
            name: '',
            port: ''
        })
    }

Now, fill the values and submit the form.  Open your console panel and see the response.

 

Success Response

Also, now check the database and see the values.

React Node js tutorial

 

So, our data is added successfully.

Step 11: Display the server data.

Write the following code inside IndexComponent.js file.

// IndexComponent.js

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

export default class IndexComponent extends Component {

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

    render() {
      return (
        <div className="container">
            <table className="table table-striped">
              <thead>
                <tr>
                  <td>ID</td>
                  <td>Name</td>
                  <td>Port</td>
                </tr>
              </thead>
              <tbody>
                {this.tabRow()}
              </tbody>
            </table>
        </div>
      );
    }
  }

Okay, now write the stateless component, and that is TableRow.js component, which we need to create inside components folder.

// TableRow.js

import React, { Component } from 'react';

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

export default TableRow;

Step 12: Edit and update the data.

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 EditComponent.js file.

// EditComponent.js

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

export default class EditComponent extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {name: '', port: ''};
    }

    componentDidMount() {
        axios.get('http://localhost:4200/serverport/edit/'+this.props.match.params.id)
            .then(response => {
                this.setState({ name: response.data.name, port: response.data.port });
            })
            .catch(function (error) {
                console.log(error);
            })
        }

    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        const serverport = {
            name: this.state.name,
            port: this.state.port
        }
        axios.post('http://localhost:4200/serverport/update/'+this.props.match.params.id, serverport)
        .then(res => console.log(res.data));
        this.setState({
            name: '',
            port: ''
        })
        this.props.history.push('/index');
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Edit New Server</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" value={this.state.name} className="form-control" onChange={this.onChangeHostName}/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" value={this.state.port} className="form-control" onChange={this.onChangePort}/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Update server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Here, you can see that our data is updated successfully. Now, the only thing remaining is deleting. So create 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:4200/serverport/delete/'+this.props.obj._id)
            .then(console.log('Deleted'))
            .catch(err => console.log(err))
    }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj._id}
          </td>
          <td>
            {this.props.obj.name}
          </td>
          <td>
            {this.props.obj.port}
          </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;

 

React CRUD Functionality

Finally, our React Express Tutorial Example From Scratch is over. Thanks for taking this example.

Fork Me On Github

 

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

]]>
https://appdividend.com/2018/04/05/react-express-tutorial-example/feed/ 8
MongoDB Node js Rest API Example Tutorial https://appdividend.com/2018/03/31/mongodb-node-js-rest-api-example/ https://appdividend.com/2018/03/31/mongodb-node-js-rest-api-example/#comments Sat, 31 Mar 2018 08:00:15 +0000 http://localhost:8888/wordpress/?p=228 MongoDB Node js Rest API Example Tutorial

MongoDB Node js Rest API Example Tutorial is the topic, we will discuss today.  REST APIs handle the server side of the web application. That means that the backend is built once and can provide content or data for the frontend apps like Angular, React or Vue, mobile platforms like Android, iOS or React Native, or other […]

The post MongoDB Node js Rest API Example Tutorial appeared first on AppDividend.

]]>
MongoDB Node js Rest API Example Tutorial

MongoDB Node js Rest API Example Tutorial is the topic, we will discuss today.  REST APIs handle the server side of the web application. That means that the backend is built once and can provide content or data for the frontend apps like Angular, React or Vue, mobile platforms like Android, iOS or React Native, or other server-side apps. REST stands for Representational State Transfer, and it is the way how the web server should respond to the requests. It allows to read, create, update and delete the data from the database. MongoDB Node js Rest API Example Tutorial is bit long, so stay with me.

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

Technology Stack

  1. Node.js as a platform
  2. Express as a node.js web framework
  3. MongoDB as a NoSQL Database

Step 1: Installing Node.js on Mac

Go to the terminal and type the following command.

node -v

If you have previously installed Node.js, then it will give you the version that is installed on your mac, if you can’t find then you do need to install it. So let’s assume that you have not installed, so install using the following command. Of course, you can go to nodejs.org and download the mac package, but you can also pull it through homebrew. For that, you have installed homebrew on your machine, and it is straightforward.

Install Node.js and npm with Homebrew

First, install Homebrew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run brew update to make sure Homebrew is up to date.

Next, add Homebrew’s location to your $PATH  in your .bash_profile or .zshrc file.

export PATH="/usr/local/bin:$PATH"

Next, install Node.js. It will install npm also with that.

brew install node

Now, test by typing the following command.

node -v
npm -v

Install Node.js on mac

Install MongoDB using homebrew.

Type the following command in your terminal.

brew install mongodb

After downloading Mongo, create the “db” directory. This is where the Mongo data files will live. You can create the directory in the default location by running mkdir -p /data/db

Make sure that the /data/db directory has the right permissions by running the following command.

sudo chown -R `id -un` /data/db

Run the Mongo daemon, in one of your terminal windows run mongod. This should start the Mongo server at port number 27017

mongod

 

Install MongoDB on mac

Run the Mongo shell, with the Mongo daemon running in one terminal, type mongo in another terminal window. This will run the Mongo shell which is an application to access data in MongoDB.

mongo

Start MongoDB on MAC

I have typed the one command to show the default database in the MongoDB, and there are three databases by default.

Step 2: Crafting a new Node.js application.

Okay, now Node.js and MongoDB are correctly installed on our machine. Now, it is time to create a project folder. We will use Yarn package manager to install the dependencies. It is designed by Facebook. First, if you have not installed Yarn previously then install by the following command.

brew install yarn

Test that Yarn is installed by running:

yarn -v

It will give you the version and by checking that we ensure that we have successfully installed yarn on our machine.

MongoDB Node js Rest API Example

Create a project folder and go into that.

mkdir mongorest
cd mongorest

Now, open that folder in your favorite code editor. In my case, it is Visual Studio Code. It is the best code editor for Javascript development in my opinion. Now, install the following packages using yarn.

yarn add express

Express is a web framework that built top on Node.js. It is very lightweight and has all the features that any modern framework has. We will make a simple API that can add the course name and price in the database. The course user can add, edit and update and delete their courses.

Now, install the other dependencies like mongoose, nodemon, and body-parser.

yarn add mongoose body-parser

Install nodemon as a global dependency. We need this because every time we change the file, it restarts the server automatically. So we do not do it manually.

sudo yarn global add nodemon

Create a server.js file inside the root of the project. Define and start the server.

// server.js

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

const PORT = 4000;

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT: ',PORT);
});

Go to the package.json file and add the scripts object.

{
  "scripts": {
    "start": "nodemon server.js"
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongoose": "^5.0.12",
    "nodemon": "^1.17.3"
  }
}

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

npm start

Start Node js server in mac

Step 3: Connect Node js application to MongoDB.

Create one file inside root called db.js. Export db object from db.js file.

// db.js

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

It is our connection string in which username and password are empty. Our database name is mongorestapi.

Import db.js file inside the server.js file. Remeber you have already run the MongoDB server at port 27017. If you have closed previously then start by typing mongod command.

// server.js

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

const app = express();
const config = require('./db');
const PORT = 4000;

app.use(bodyParser.json());

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

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

Save the file and switch to the terminal. You can see that our application is connected to the MongoDB database. Note that, we have not created the database in the MongoDB at this time, but still our application is connected. It is right, when we insert any values in the database, then the database itself and its collection will create in the MongoDB. We have also imported body-parser module to parse the data from the form. Use that module as a middleware so every incoming post request can be parsed.

Step 4: Create Model for our application.

Now, we need to create two folders in a root called routes and models.

In models folder, create one model called Course.js. We define the schema for the courses collection. We use Mongoose library for that since it is the best ORM to manipulate the MongoDB database.

// Course.js

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

// Define collection and schema for Course
var Course = new Schema({
  course_name: {
    type: String
  },
  course_price: {
    type: Number
  }
},{
    collection: 'courses'
});

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

Now, import Course.js file inside server.js.

// server.js

const Course = require('./models/Course');

Step 5: Create routes for our application.

In the routes folder, create one file called CourseRoute.js file.

Now, in that file, we need to import Course.js model as well as express to get Router module.

We will save the values in the database via Mongoose model, so it is required.

// CourseRoute.js

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

const Course = require('../models/Course');

router.route('/add').post(function (req, res) {
    const course = new Course(req.body);
    course.save()
      .then(course => {
      res.status(200).json({'course': 'Course added successfully'});
      })
      .catch(err => {
      res.status(400).send("unable to save the course into database");
      });
  });

module.exports = router;

We have used Router module from express and required the model to save the data in the MongoDB database. Created one route that says that any post request hit  /course/add URL pattern execute that function. It will create an instance of the model and save that data in the database via object-relational mapping.  Now, we need to tell express that hit any request that has resource /course, so this file CourseRoute.js file’s function executed.

So our server.js file looks like this.

// server.js

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

const app = express();
const config = require('./db');
const Course = require('./models/Course');
const CourseRoute = require('./routes/CourseRoute');

const PORT = 4000;

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

app.use(bodyParser.json());
app.use('/course', CourseRoute);

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

Here, I have used middleware to redirect any request that has a pattern like ‘/course’ to the CourseRoute.js. So if the request is something like ‘/course/add’ and type is the POST then we can save the data in the database.

// server.js

app.use('/course', CourseRoute);

Now, we can test this in the Postman. So open the Postman. It is the handy tool that can be used to test the API. Remember, you need to POST the data as a raw json format.

Postman API Tutorial

We can see in the response that, we have successfully inserted the values in the database. Now, check in the MongoDB database. Open your mongoshell, if you have not opened then type mongo in the terminal. Now, type the one by one command in your terminal. First, type the following.

show dbs

It will show all of the databases. You can see in the list that our database mongorestapi is created. Now type the following command.

use mongorestapi

So it will switch to the mongorestapi database.

MongoDB Rest API Tutorial

Now, we need to confirm that whether our values are inserted or not. So we need to query the database to show existing collections if any.

show collections

It will tell us, we have courses collection. So switch to courses collection.

use courses

Now, fetch all the documents inside courses collection.

db.courses.find().pretty()

It will give all the collections that have already saved in the database. It dumps all the results in a prettier format.

Fetch all the collections data from the database

If you find empty or nothing, please check your post request in the Postman. You can see my screenshot as well to compare with yours.

Okay, so reading and creating is done. Remaining is Updating and deleting. So, let us do that.

// CourseRoute.js

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

const Course = require('../models/Course');

router.route('/add').post(function (req, res) {
    const course = new Course(req.body);
    course.save()
      .then(course => {
      console.log(course);    
      res.status(200).json({'course': 'Course added successfully'});
      })
      .catch(err => {
      res.status(400).send("unable to save the course into database");
      });
  });

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

  //  Defined update route
  router.route('/update/:id').post(function (req, res) {
    Course.findById(req.params.id, function(err, course) {
      if (!course)
        return next(new Error('Could not load Document'));
      else {
        course.course_name = req.body.course_name;
        course.course_price = req.body.course_price;
  
        course.save().then(course => {
            res.json('Successfully Updated');
        })
        .catch(err => {
              res.status(400).send("unable to update the database");
        });
      }
    });
  });
  
  // Defined delete | remove | destroy route
  router.route('/delete/:id').get(function (req, res) {
    Course.findByIdAndRemove({_id: req.params.id}, function(err, course){
          if(err) res.json(err);
          else res.json('Successfully removed');
      });
  });

module.exports = router;

Now, you check yourself and test all the routes in the Postman.

So finally, MongoDB Node js Rest API Example is over. This post is a bit of long, but I have tried my best to show everything from scratch. Hope you enjoy it. If some concepts are remaining then I will cover in upcoming posts. So stay tuned.

The post MongoDB Node js Rest API Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/03/31/mongodb-node-js-rest-api-example/feed/ 9