Web applications in React, Bootstrap, MongoDB, Express/Create a Node Express web server locally that connects to a MongoDB database

Installing Node.Js and Express Generator

edit
  • 1) Node.Js is a Javascript framework that also allows you to write server-side code and therefore, in particular, allows you to create an Express web server. npm (short for Node Package Manager [2]) is the default package manager for the Node.js JavaScript runtime environment. It consists of a command line client, also called npm, and an online database of public and private packages, called the npm registry.
  • 2) Install Node.js on your PC from here: https://nodejs.org/
  • 3) In the terminal type:
node -v
npm -v

to verify that both node and npm have been installed correctly on your system.

  • 4) Install the express-generator package via npm by typing in the terminal:
npm install express-generator -g
  • 5) Open the terminal in Documents and type:
express ItemsServer
  • 6) In the ItemsServer folder, type in the terminal:
npm install
  • 7) In the ItemsServer folder type in the terminal to start the server:
npm start
  • 8) In the browser at the link http://localhost:3000/ the message "Welcome to Express" will appear.A Node Express web server is done !

API REST and MONGOOSE

edit

The requests that the client makes to the server are made through the REST API. For example, if you are making a GET request, you are asking the server to return a resource. If you make a POST request, the server is being asked to create a new resource. If you are making a PUT request, you are asking the server to update an existing resource. And if you issue a DELETE request, the server is being asked to delete the resource identified by the particular URI. The exchange of data between client and server takes place in JSON format, which represents the standard with which Javascript objects are built. For example, the URL http://localhost:3000/items/234 means that the client asks the server to act on item 234, on which it is possible to perform GET, PUT or DELETE operations. To implement REST API calls on the MongoDB database you need to install mongoose:

  • 1) In the ItemsServer folder open a terminal and type:
npm install mongoose@5.7.0 –save
  • 2) Create a mongoose schema for the document items of the MongoDB database and insert it in the items.js file inside the models sub folder of the ItemServer folder
// items.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var itemSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    quantity: {
        type: Number,
        required: true
    },
    measure: {
        type: String,
        required: true
    }
},    {
    timestamps: true
});

var Items = mongoose.model('Item', itemSchema);

module.exports = Items;
  • 3) In the subFolder routes of ItemServer, create the file itemRouter.js :
// itemRouter.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const Items = require('../models/items');

const itemRouter = express.Router();

itemRouter.use(bodyParser.json());

itemRouter.route('/')
.get((req,res,next) => {
    Items.find({})
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
})
.post((req, res, next) => {
    Items.create(req.body)
    .then((resp) => {
        console.log('Item Created ', resp);
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
})
.put((req, res, next) => {
    res.statusCode = 403;
    res.end('PUT operation not supported on /items');
})
.delete((req, res, next) => {
    Items.remove({})
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));    
});

itemRouter.route('/:itemId')
.get((req,res,next) => {
    Items.findById(req.params.itemId)
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
})
.post((req, res, next) => {
    res.statusCode = 403;
    res.end('POST operation not supported on /items/'+ req.params.itemId);
})
.put((req, res, next) => {
    Items.findByIdAndUpdate(req.params.itemId, {
        $set: req.body
    }, { new: true })
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
})
.delete((req, res, next) => {
    Items.findByIdAndRemove(req.params.itemId)
    .then((resp) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(resp);
    }, (err) => next(err))
    .catch((err) => next(err));
});

module.exports = itemRouter;
  • 4) Edit the app.js file in the ItemsServer folder :
// app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var itemsRouter = require('./routes/itemRouter');

var app = express();

const mongoose = require('mongoose');


mongoose.Promise = require('bluebird');

const url = 'mongodb://localhost:27017/db_items';

const options = {
  useMongoClient: true,
  autoIndex: false, // Don't build indexes
  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};

mongoose.connect(url, options);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
  });

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/items', itemsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
  • 5) We created a Node Express web server that connects locally to a MongoDB database.