Call GET HTTP Method with Express.JS Web API and MongoDB


Create a database with the name is learn_reactjs. This database have 1 collection: Product collection

/* Create learn_reactjs database */
use learn_reactjs

/* Create Product collection */
db.createCollection('product');

/* Dumping data for `product` collection */
/* 1 */
{
    "_id" : ObjectId("59eb397591876fae6628f17d"),
    "name" : "Mobile 1",
    "price" : 2.0,
    "quantity" : 4.0,
    "status" : true
}

/* 2 */
{
    "_id" : ObjectId("59eb3a3991876fae6628f17e"),
    "name" : "Mobile 2",
    "price" : 5.0,
    "quantity" : 2.0,
    "status" : false
}

/* 3 */
{
    "_id" : ObjectId("5a73bcda0f628d50d9dfe0a9"),
    "name" : "Laptop 2",
    "price" : 9,
    "quantity" : 3,
    "status" : true
}

/* 4 */
{
    "_id" : ObjectId("5a73bd120f628d50d9dfe0c6"),
    "name" : "Computer 1",
    "price" : 15,
    "quantity" : 8,
    "status" : false
}

/* 5 */
{
    "_id" : ObjectId("5a73e2f3ca031628a0701926"),
    "name" : "Computer 2",
    "price" : 20,
    "quantity" : 8,
    "status" : true
}




Create LearnReactJSWithRealApps_Server folder and select to this folder in Visual Studio Code

Use the following command to install Mongoose:

npm install mongoose --save

Use the following command to install Express.JS:

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save

Create schemas folder in Node project. Create product.schema.js file into schemas folder. Declare schema for product collection as below:

var mongoose = require('mongoose');

var ProductSchema = new mongoose.Schema(
    {
      name: String,
      price: Number,
      quantity: Number,
      status: Boolean
    },
    {
        versionKey: false
    }
);

module.exports = mongoose.model('Product', ProductSchema, 'product');

Create a new folder named api inside the server project. Create product.api.js file inside api folder contains Rest APIs provides application/json data for the client

var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');

var ProductAPI = {
    findAll: function (request, response) {
        Product.find({}, function (error, products) {
            if (error) {
                throw error;
            } else {
                response.status(200).json(products);
            }
        });
    }
};

module.exports = ProductAPI;




Inside the api folder create a new file named index.js. This file will hold all the routes needed for rest api in server.

var express = require('express');
var mongoose = require('mongoose');

var router = express.Router();

mongoose.connect('mongodb://localhost:27017/learn_reactjs');

var ProductAPI = require('./product.api');

router.get('/product/findAll', ProductAPI.findAll);

module.exports = router;

At the root of server project, create a file named server.js. This will be the entry point into node application. This will start the server and listen on a local port

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

app.all('/*', function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
	res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
	if (req.method == 'OPTIONS') {
		res.status(200).end();
	} else {
		next();
	}
});

app.use('/api', require('./api/index'));

var server = app.listen(9090, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log("Server listening at http://%s:%s", host, port)
});

At the root of server project run command: node server.js

Access Rest API use the following url: http://localhost:9090/api/product/findAll

Output

[
    {"_id":"59eb397591876fae6628f17d","name":"Mobile 1","price":2,"quantity":4,"status":true},
    {"_id":"59eb3a3991876fae6628f17e","name":"Mobile 2","price":5,"quantity":2,"status":false},
    {"_id":"5a73bcda0f628d50d9dfe0a9","name":"Laptop 2","price":9,"quantity":3,"status":true},
    {"_id":"5a73bd120f628d50d9dfe0c6","name":"Computer 1","price":15,"quantity":8,"status":false},
    {"_id":"5a73e2f3ca031628a0701926","name":"Computer 2","price":20,"quantity":8,"status":true}
]

Create new folder named LearnReactJSWithRealApps and select to this folder in
Visual Studio Code

Open Terminal windows in Visual Studio Code and type:

npm install -g babel
npm install -g babel-cli
npm install webpack --save
npm install webpack-dev-server --save
npm install react --save
npm install react-dom --save
npm install --save-dev style-loader
npm install --save-dev css-loader

In assets folder, create new folder named css. In this folder, create new css file named style.css as below:

table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}




In root folder of project, create new folder src\components. In this folder, create new file named product.component.jsx as below:

import React from 'react';

import styles from '../../assets/css/style.css';

class ProductComponent extends React.Component {

    constructor() {
        super();
        this.state = {
            products: []
        };
    }

    componentDidMount() {
        fetch('http://localhost:9090/api/product/findall')
            .then(res => res.json())
            .then(res => {
                this.setState({
                    products: res
                });
            })
            .catch(error => {
                console.log(error)
            });
    }

    render() {
        return (
            <div>
                <h3>Product List</h3>
                <table cellPadding="3" cellSpacing="3">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Status</th>
                            <th>Price</th>
                            <th>Quantity</th>
                            <th>Sub Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.products.map(function (p, index) {
                            return (
                                <tr>
                                    <td>{p._id}</td>
                                    <td>{p.name}</td>
                                    <td>{p.status}</td>
                                    <td>{p.price}</td>
                                    <td>{p.quantity}</td>
                                    <td>{p.price * p.quantity}</td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        );
    }

}

export default ProductComponent;

In root folder of project, create new file named main.js as below:

import React from 'react';
import ReactDOM from 'react-dom';

import ProductComponent from './src/components/product.component.jsx';

ReactDOM.render(<ProductComponent />, document.getElementById('app'));

In root folder of project, create new file named webpack.config.js as below:

var config = {
    entry: './main.js',

    output: {
        path: __dirname,
        filename: 'index.js',
    },

    devServer: {
        inline: true,
        port: 8081 // server port
    },

    module: {
        loaders: [
            {
                test: /\.css$/,
                loader: 'style-loader'
            },
            {
                test: /\.css$/,
                loader: 'css-loader',
                query: {
                    modules: true,
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                }
            },
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
}

module.exports = config;

In root folder of project, create new file named index.html as below:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Learn ReactJS With Real Apps</title>
</head>
<body>

    <div id="app"></div>
    <script src="index.js"></script>

</body>
</html>

In root folder of project, create new file named package.json as below:

{
  "name": "learnreactjswithrealapps",
  "version": "1.0.0",
  "description": "Learn ReactJS With Real Apps",
  "main": "main.js",
  "dependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  },
  "devDependencies": {
    "css-loader": "^0.28.11",
    "style-loader": "^0.21.0"
  },
  "scripts": {
    "start": "webpack-dev-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/reactjs/react-tutorial.git"
  },
  "keywords": [
    "react"
  ],
  "author": "PMK Lab",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/reactjs/react-tutorial/issues"
  },
  "homepage": "https://github.com/reactjs/react-tutorial#readme"
}




In Terminal windows in Visual Studio Code and type: npm start,
program will open url http://localhost:8081/ on browser