Call PUT 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 = {

    update: function (request, response) {

        Product.findByIdAndUpdate(
            request.body._id,
            {
                name: request.body.name,
                price: request.body.price,
                quantity: request.body.quantity,
                status: request.body.status
            },
            function (error, result) {
                if (error) {
                    throw error;
                } else {
                    response.status(200).json(result);
                }
            }
        );
    }

};


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.put('/product/update', ProductAPI.update);

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

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

class ProductComponent extends React.Component {

    constructor() {
        super();
        this.state = {
            _id: '',
            name: '',
            price: 0,
            quantity: 0,
            status: true
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        let value = target.value;
        if (target.type === 'checkbox') {
            value = target.checked;
        }
        const name = target.name;
        this.setState({
            [name]: value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        fetch('http://localhost:9090/api/product/update', {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(this.state)
        })
        .then(function (resp) {
            alert('Done');
        });
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit.bind(this)}>
                    <h3>Update Product</h3>
                    <table cellPadding="2" cellSpacing="2">
                        <tr>
                            <td>Id</td>
                            <td><input type="text" name="_id" value={this.state._id} onChange={this.handleChange} /></td>
                        </tr>
                        <tr>
                            <td>Name</td>
                            <td><input type="text" name="name" value={this.state.name} onChange={this.handleChange} /></td>
                        </tr>
                        <tr>
                            <td>Price</td>
                            <td><input type="text" name="price" value={this.state.price} onChange={this.handleChange} /></td>
                        </tr>
                        <tr>
                            <td>Quantity</td>
                            <td><input type="text" name="quantity" value={this.state.quantity} onChange={this.handleChange} /></td>
                        </tr>
                        <tr>
                            <td>Status</td>
                            <td>
                                <input type="checkbox" name="status" checked={this.state.status} onChange={this.handleChange} />
                            </td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td><input type="submit" value="Save" /></td>
                        </tr>
                    </table>
                </form>
            </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