Full download Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node 1st Edition Vasan Subramanian (Auth.) pdf docx
Full download Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node 1st Edition Vasan Subramanian (Auth.) pdf docx
com
https://textbookfull.com/product/pro-mern-stack-full-stack-
web-app-development-with-mongo-express-react-and-node-1st-
edition-vasan-subramanian-auth/
OR CLICK BUTTON
DOWNLOAD NOW
Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node 2nd Edition Vasan Subramanian
https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-2nd-edition-vasan-
subramanian/
textboxfull.com
Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node 1st Edition Vasan Subramanian
(Auth.)
https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-1st-edition-vasan-
subramanian-auth/
textboxfull.com
https://textbookfull.com/product/full-stack-react-projects-modern-web-
development-using-react-16-node-express-and-mongodb-2nd-edition-shama-
hoque/
textboxfull.com
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/
textboxfull.com
React Architect Full Stack React App Development and
Serverless Deployment Frank Zickert
https://textbookfull.com/product/react-architect-full-stack-react-app-
development-and-serverless-deployment-frank-zickert/
textboxfull.com
https://textbookfull.com/product/mastering-full-stack-react-web-
development-1st-edition-tomasz-dyl/
textboxfull.com
https://textbookfull.com/product/web-development-with-node-and-
express-leveraging-the-javascript-stack-2nd-edition-ethan-brown/
textboxfull.com
https://textbookfull.com/product/modern-full-stack-development-using-
typescript-react-node-js-webpack-and-docker-zammetti/
textboxfull.com
Vasan Subramanian
Pro MERN Stack
Vasan Subramanian
Bangalore, Karnataka, India
ISBN-13 (pbk): 978-1-4842-2652-0 ISBN-13 (electronic): 978-1-4842-2653-7
DOI 10.1007/978-1-4842-2653-7
Library of Congress Control Number: 2017933833
Copyright © 2017 by Vasan Subramanian
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole
or part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical
way, and transmission or information storage and retrieval, electronic adaptation, computer
software, or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even
if they are not identified as such, is not to be taken as an expression of opinion as to whether or
not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the
date of publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Pramila Balan
Development Editor: Poonam Jain
Technical Reviewer: Anshul Chanchlani
Coordinating Editor: Prachi Mehta
Copy Editor: Mary Behr
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover image designed by Freepik
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.
com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions
and licenses are also available for most titles. For more information, reference our Print and eBook
Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/978-1-4842-2652-0.
For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
To Sandeep and Fazle.
Contents at a Glance
■
■Chapter 1: Introduction������������������������������������������������������������������ 1
■
■Chapter 2: Hello World������������������������������������������������������������������ 17
■
■Chapter 3: React Components������������������������������������������������������ 37
■
■Chapter 4: React State������������������������������������������������������������������ 55
■
■Chapter 5: Express REST APIs������������������������������������������������������ 69
■
■Chapter 6: Using MongoDB����������������������������������������������������������� 93
■
■Chapter 7: Modularization and Webpack����������������������������������� 115
■
■Chapter 8: Routing with React Router���������������������������������������� 151
■
■Chapter 9: Forms������������������������������������������������������������������������ 173
■
■Chapter 10: React-Bootstrap������������������������������������������������������ 207
■
■Chapter 11: Server Rendering���������������������������������������������������� 245
■
■Chapter 12: Advanced Features������������������������������������������������� 275
■
■Chapter 13: Looking Ahead�������������������������������������������������������� 319
Index���������������������������������������������������������������������������������������������� 325
v
Contents
■
■Chapter 1: Introduction������������������������������������������������������������������ 1
What Is MERN?���������������������������������������������������������������������������������������� 1
Who Should Read This Book�������������������������������������������������������������������� 2
Structure of the Book������������������������������������������������������������������������������ 2
Conventions��������������������������������������������������������������������������������������������� 3
What You Need���������������������������������������������������������������������������������������� 5
MERN Components���������������������������������������������������������������������������������� 5
React������������������������������������������������������������������������������������������������������������������������ 5
Node.js���������������������������������������������������������������������������������������������������������������������� 7
Express��������������������������������������������������������������������������������������������������������������������� 9
MongoDB���������������������������������������������������������������������������������������������������������������� 10
Tools and Libraries������������������������������������������������������������������������������������������������� 12
Why MERN?������������������������������������������������������������������������������������������� 13
JavaScript Everywhere������������������������������������������������������������������������������������������� 13
JSON Everywhere��������������������������������������������������������������������������������������������������� 14
Node.js Performance���������������������������������������������������������������������������������������������� 14
The npm Ecosystem����������������������������������������������������������������������������������������������� 14
Isomorphic�������������������������������������������������������������������������������������������������������������� 14
It’s not a Framework!��������������������������������������������������������������������������������������������� 15
Summary����������������������������������������������������������������������������������������������� 15
vii
■ Contents
■
■Chapter 2: Hello World������������������������������������������������������������������ 17
Server-Less Hello World������������������������������������������������������������������������ 17
Server Setup����������������������������������������������������������������������������������������� 20
nvm������������������������������������������������������������������������������������������������������������������������� 21
Node.js�������������������������������������������������������������������������������������������������������������������� 21
Project�������������������������������������������������������������������������������������������������������������������� 22
npm������������������������������������������������������������������������������������������������������������������������ 22
Express������������������������������������������������������������������������������������������������������������������� 24
Build-Time JSX Compilation������������������������������������������������������������������ 26
Separate Script File������������������������������������������������������������������������������������������������ 27
Transform��������������������������������������������������������������������������������������������������������������� 28
Automate���������������������������������������������������������������������������������������������������������������� 29
React Library���������������������������������������������������������������������������������������������������������� 30
ES2015�������������������������������������������������������������������������������������������������� 30
Summary����������������������������������������������������������������������������������������������� 33
Answers to Exercises���������������������������������������������������������������������������� 34
Exercise: JSX���������������������������������������������������������������������������������������������������������� 34
Exercise: npm��������������������������������������������������������������������������������������������������������� 34
Exercise: Express���������������������������������������������������������������������������������������������������� 35
Exercise: Babel������������������������������������������������������������������������������������������������������� 35
Exercise: ES2015���������������������������������������������������������������������������������������������������� 36
■
■Chapter 3: React Components������������������������������������������������������ 37
Issue Tracker����������������������������������������������������������������������������������������� 37
React Classes���������������������������������������������������������������������������������������� 38
Composing Components����������������������������������������������������������������������� 40
viii
■ Contents
Passing Data����������������������������������������������������������������������������������������� 42
Using Properties����������������������������������������������������������������������������������������������������� 42
Property Validation������������������������������������������������������������������������������������������������� 44
Using Children�������������������������������������������������������������������������������������������������������� 45
Dynamic Composition��������������������������������������������������������������������������� 47
Summary����������������������������������������������������������������������������������������������� 51
Answers to Exercises���������������������������������������������������������������������������� 51
Exercise: React Classes������������������������������������������������������������������������������������������ 51
Exercise: Passing Data������������������������������������������������������������������������������������������� 52
Exercise: Dynamic Composition����������������������������������������������������������������������������� 52
■
■Chapter 4: React State������������������������������������������������������������������ 55
Setting State������������������������������������������������������������������������������������������ 55
Async State Initialization����������������������������������������������������������������������� 58
Event Handling�������������������������������������������������������������������������������������� 60
Communicating from Child to Parent���������������������������������������������������� 60
Stateless Components�������������������������������������������������������������������������� 63
Designing Components������������������������������������������������������������������������� 65
State vs. props�������������������������������������������������������������������������������������������������������� 65
Component Hierarchy��������������������������������������������������������������������������������������������� 65
Communication������������������������������������������������������������������������������������������������������� 66
Stateless Components�������������������������������������������������������������������������������������������� 66
Summary����������������������������������������������������������������������������������������������� 66
Answers to Exercises���������������������������������������������������������������������������� 67
Exercise: Setting State������������������������������������������������������������������������������������������� 67
Exercise: Communicate Child to Parent������������������������������������������������������������������ 68
ix
■ Contents
■
■Chapter 5: Express REST APIs������������������������������������������������������ 69
REST������������������������������������������������������������������������������������������������������ 69
Resource Based������������������������������������������������������������������������������������������������������ 69
HTTP Methods as Actions��������������������������������������������������������������������������������������� 70
JSON����������������������������������������������������������������������������������������������������������������������� 71
Express�������������������������������������������������������������������������������������������������� 72
Routing������������������������������������������������������������������������������������������������������������������� 72
Handler Function���������������������������������������������������������������������������������������������������� 73
Middleware������������������������������������������������������������������������������������������������������������� 75
■
■Chapter 6: Using MongoDB����������������������������������������������������������� 93
MongoDB Basics����������������������������������������������������������������������������������� 93
Documents������������������������������������������������������������������������������������������������������������� 93
Collections�������������������������������������������������������������������������������������������������������������� 94
Query Language����������������������������������������������������������������������������������������������������� 94
x
■ Contents
Installation�������������������������������������������������������������������������������������������������������������� 95
The mongo Shell����������������������������������������������������������������������������������������������������� 95
Shell Scripting�������������������������������������������������������������������������������������������������������� 99
Schema Initialization����������������������������������������������������������������������������� 99
MongoDB Node.js Driver��������������������������������������������������������������������� 101
Callbacks�������������������������������������������������������������������������������������������������������������� 103
Promises��������������������������������������������������������������������������������������������������������������� 104
Generator and co Module������������������������������������������������������������������������������������� 104
The async Module������������������������������������������������������������������������������������������������� 105
■
■Chapter 7: Modularization and Webpack����������������������������������� 115
Server-Side Modules��������������������������������������������������������������������������� 115
Introduction to Webpack��������������������������������������������������������������������� 117
Using Webpack Manually�������������������������������������������������������������������� 118
Transform and Bundle������������������������������������������������������������������������� 120
Libraries Bundle���������������������������������������������������������������������������������� 125
Hot Module Replacement�������������������������������������������������������������������� 129
HMR Using Middleware����������������������������������������������������������������������� 132
Comparison of HMR Alternatives�������������������������������������������������������������������������� 133
Debugging������������������������������������������������������������������������������������������� 134
Server-Side ES2015���������������������������������������������������������������������������� 135
xi
■ Contents
ESLint�������������������������������������������������������������������������������������������������� 140
Environment��������������������������������������������������������������������������������������������������������� 142
Summary��������������������������������������������������������������������������������������������� 147
Answers to Exercises�������������������������������������������������������������������������� 148
Exercise: Transform and Bundle��������������������������������������������������������������������������� 148
Exercise: Hot Module Replacement���������������������������������������������������������������������� 148
Exercise: Server-Side ES2015������������������������������������������������������������������������������ 149
Exercise: ESLint���������������������������������������������������������������������������������������������������� 150
■
■Chapter 8: Routing with React Router���������������������������������������� 151
Routing Techniques����������������������������������������������������������������������������� 152
Simple Routing������������������������������������������������������������������������������������ 152
Route Parameters�������������������������������������������������������������������������������� 154
Route Query String������������������������������������������������������������������������������ 157
Programmatic Navigation�������������������������������������������������������������������� 161
Nested Routes������������������������������������������������������������������������������������� 164
Browser History����������������������������������������������������������������������������������� 167
Summary��������������������������������������������������������������������������������������������� 169
Answers to Exercises�������������������������������������������������������������������������� 169
Exercise: Route Parameters���������������������������������������������������������������������������������� 169
Exercise: Route Query String�������������������������������������������������������������������������������� 169
Exercise: Programmatic Navigation���������������������������������������������������������������������� 170
■
■Chapter 9: Forms������������������������������������������������������������������������ 173
More Filters in the List API������������������������������������������������������������������ 173
Filter Form������������������������������������������������������������������������������������������� 174
The Get API������������������������������������������������������������������������������������������ 180
Edit Page��������������������������������������������������������������������������������������������� 182
xii
■ Contents
UI Components������������������������������������������������������������������������������������ 186
Number Input�������������������������������������������������������������������������������������������������������� 186
Date Input������������������������������������������������������������������������������������������������������������� 190
■
■Chapter 10: React-Bootstrap������������������������������������������������������ 207
Bootstrap Installation�������������������������������������������������������������������������� 207
Navigation������������������������������������������������������������������������������������������� 210
Table and Panel����������������������������������������������������������������������������������� 216
Forms�������������������������������������������������������������������������������������������������� 218
Grid-Based Forms������������������������������������������������������������������������������������������������� 218
Inline Forms���������������������������������������������������������������������������������������������������������� 222
Horizontal Forms�������������������������������������������������������������������������������������������������� 224
Alerts��������������������������������������������������������������������������������������������������� 229
Validations������������������������������������������������������������������������������������������������������������ 229
Results������������������������������������������������������������������������������������������������������������������ 231
Modals������������������������������������������������������������������������������������������������� 237
Summary��������������������������������������������������������������������������������������������� 242
xiii
■ Contents
■
■Chapter 11: Server Rendering���������������������������������������������������� 245
Basic Server Rendering����������������������������������������������������������������������� 245
Handling State������������������������������������������������������������������������������������� 250
Initial State������������������������������������������������������������������������������������������ 252
Server-Side Bundle����������������������������������������������������������������������������� 254
Back-End HMR������������������������������������������������������������������������������������ 256
Routed Server Rendering�������������������������������������������������������������������� 260
Encapsulated Fetch����������������������������������������������������������������������������� 268
Summary��������������������������������������������������������������������������������������������� 272
Answers to Exercises�������������������������������������������������������������������������� 273
Back-End HMR������������������������������������������������������������������������������������������������������ 273
Routed Server Rendering������������������������������������������������������������������������������������� 273
■
■Chapter 12: Advanced Features������������������������������������������������� 275
MongoDB Aggregate��������������������������������������������������������������������������� 275
Pagination������������������������������������������������������������������������������������������� 284
Higher Order Components������������������������������������������������������������������� 288
Search Bar������������������������������������������������������������������������������������������� 297
Google Sign-In������������������������������������������������������������������������������������� 303
Session Handling��������������������������������������������������������������������������������� 310
Summary��������������������������������������������������������������������������������������������� 317
xiv
■ Contents
■
■Chapter 13: Looking Ahead�������������������������������������������������������� 319
Mongoose�������������������������������������������������������������������������������������������� 319
Flux������������������������������������������������������������������������������������������������������ 320
Deployment����������������������������������������������������������������������������������������� 322
mern.io������������������������������������������������������������������������������������������������ 323
That’s All, Folks!���������������������������������������������������������������������������������� 324
Index���������������������������������������������������������������������������������������������� 325
xv
About the Author
xvii
CHAPTER 1
Introduction
Web application development is not what it used to be even a couple of years back.
Today, there are so many options, and the uninitiated are often confused about what’s
good for them. This applies not just to the broad stack (the various tiers or technologies
used), but also to the tools that aid in development; there are so many choices. This book
stakes a claim that the MERN stack is great for developing a complete web application,
and it takes the reader through all that is necessary to get it done.
In this chapter, I’ll give a broad overview of the technologies that make up the MERN
stack. I won’t go into details or examples in this chapter; I’ll just introduce the high-level
concepts. This chapter will focus on how these concepts affect an evaluation of whether
MERN is a good choice for your next web application project.
What Is MERN?
Any web application is made by using multiple technologies. The combination of these
technologies is called a “stack,” popularized by the LAMP stack, which is an acronym
for Linux, Apache, MySQL, and PHP, which are all open-source components. As web
development matured and interactivity came to the fore, single page applications (SPAs)
became more popular. An SPA is a web application paradigm that avoids refreshing a web
page to display new content; it instead uses lightweight calls to the server to get some data
or snippets and updates the web page. The result looks quite nifty when compared to the
old way of reloading the page entirely. This brought about a rise in front-end frameworks,
since much of the work was done on the client side. At approximately the same time,
although completely unrelated, NoSQL databases also started gaining popularity.
The MEAN (MongoDB, Express, AngularJS, Node.js) stack was one of the early
open-source stacks that epitomized this shift towards SPAs and the adoption of NoSQL.
AngularJS, a front-end framework based on the model-view-controller (MVC) design
pattern, anchored this stack. MongoDB, a very popular NoSQL database, was used for
persistent data storage. Node.js, a server-side JavaScript runtime environment, and
Express, a web server built on Node.js, formed the middle tier, or the web server. This
stack is arguably the most popular stack for any new web application these days.
Not exactly competing, but React, an alternate front-end technology from Facebook,
has been gaining popularity and offers a replacement to AngularJS. It thus replaces the
“A” with an “R” in MEAN, to give us the MERN Stack. I said “not exactly” since React is not
a full-fledged MVC framework. It is a JavaScript library for building user interfaces, so in
some sense it’s the View part of the MVC.
Although we pick a few defining technologies to define a stack, these are not enough
to build a complete web application. Other tools are required to help the process of
development, and other libraries are needed to complement React. This book is about all
of them: how to build a complete web application based on the MERN stack, using other
complementary tools that make it easy for us to do it.
2
Chapter 1 ■ Introduction
I have also added a checkpoint (a git branch, in fact) after every change that can be
tested in isolation, so that you can look at the exact diffs between two checkpoints, online. The
checkpoints and links to the diffs are listed in the home page (the README) of the repository.
You may find this more useful than looking at the entire source, or even the listings in the text
of this book, as GitHub diffs are far more expressive than what I can do in this book.
Rather than cover one topic or technology per section, I have adopted a more
practical and problem-solving approach. You will have developed a full-fledged working
application by the end of the book, but you’ll start small with a Hello World example.
Just as in a real project, you will add more features to the application as you progress.
When you do this, you’ll encounter tasks that need additional concepts or knowledge to
proceed. For each of these tasks, I will introduce the concept or technology that can be
used, and I’ll discuss it in detail. Thus, you may not find one chapter or section devoted
purely to one topic or technology; instead, each chapter will be a set of goals you want to
achieve in the application. You will be switching between technologies and tools as you
progress.
I have included exercises wherever possible to make you either think or look up
various documentation pages on the Internet. This is so that you know where to get
additional information for things that are not covered in the book, such as very advanced
topics or APIs.
I have chosen an issue tracking application as the application that you’ll build.
It’s something most developers can relate to, and it has many of the attributes and
requirements that any enterprise application will have, commonly referred to as a
“CRUD” application (CRUD stands for Create, Read, Update, Delete of a database record).
Conventions
Many of the conventions used in the book are quite obvious, so I won’t explain all of
them. However, I will cover some conventions with respect to how the code is shown if
they’re not obvious.
Each chapter has multiple sections, and each section is devoted to one set of code
changes that results in a working application and can be tested. One section can have
multiple listings, each of which may not be testable by itself. Every section will also have a
corresponding entry in the GitHub repository, where you can see the complete source of
the application at the end of that section, as well as the differences between the previous
section and the current section. You will find the difference view very useful to identify
the changes made in the section.
All code changes will appear in the listings within the section, but do not rely on
their accuracy. The reliable and working code can be found in the GitHub repository,
which may even have undergone last minute changes that couldn’t make it to the book in
time. All listings will have a listing caption, which will include the name of the file being
changed or created.
A listing is a full listing if it contains a file, a class, a function, or an object in its
entirety. A full listing may also contain two or more classes, functions, or objects, but not
multiple files. In such a case, if the entities are not consecutive, I’ll use ellipses to indicate
chunks of unchanged code.
Listing 1-1 is an example of a full listing, the contents of an entire file.
3
Chapter 1 ■ Introduction
app.listen(3000, function () {
console.log('App started on port 3000');
});
A partial listing, on the other hand, will not list complete files, functions, or objects.
It will start and end with an ellipsis, and will have ellipses in the middle to skip chunks of
code that have not changed. Wherever possible, the actual changes will be highlighted.
The changes will be highlighted in bold, and the unchanged code will be in the normal
font. Listing 1-2 is an example of a partial listing that has small changes.
Code blocks are used within regular text to cull out changes in code for discussion,
and are often a repetition of code in listings. These are not listings, and are often just a
line or two. The following is an example, where the line is extracted out of a listing, and
one word is highlighted:
...
const contentNode = ...
...
All commands that need to be executed on the console will be in the form a code
block starting with $. Here is an example:
4
Chapter 1 ■ Introduction
MERN Components
I’ll give a quick introduction to the main components that form the MERN stack and a few
other libraries and tools that you’ll be using to build your web application. I’ll just touch
upon the salient features, and leave the details to other chapters where they are more
appropriate.
React
React anchors the MERN stack. In some sense, it is the defining component of the MERN
stack.
React is an open-source JavaScript library maintained by Facebook that can be used
for creating views rendered in HTML. Unlike AngularJS, React is not a framework. It is a
library. Thus, it does not, by itself, dictate a framework pattern such as the MVC pattern.
You use React to render a view (the V in MVC), but how to tie the rest of the application
together is completely up to you.
I’ll discuss a few things about React that make it stand out.
5
Chapter 1 ■ Introduction
Declarative
React views are declarative. What this really means is that you, as a programmer, don’t
have to worry about managing the effect of changes in the view’s state or the data. In
other words, you don’t worry about transitions or mutations in the DOM caused by
changes to the view’s state. How does this work?
A React component declares how the view looks like, given the data. When the data
changes, if you are used to the jQuery way of doing things, you’d typically do some DOM
manipulation. Not in React. You just don’t do anything! The React library figures out
how the new view looks, and just applies the changes between the old view and the new
view. This makes the views consistent, predictable, easier to maintain, and simpler to
understand.
Won’t this be too slow? Won’t it cause the entire screen to be refreshed on every data
change? Well, React takes care of this using its virtual DOM technology. You declare
how the view looks, not in the form of HTML or a DOM, but in the form of a virtual
representation, an in-memory data structure. React can compute the differences in
the virtual DOM very efficiently, and can apply only these changes to the actual DOM.
Compared to manual updates which do only the required DOM changes, this adds very
little overhead because the algorithm to compute the differences in the virtual DOM has
been optimized to the hilt.
Component-Based
The fundamental building block of React is a component, which maintains its own state
and renders itself.
6
Chapter 1 ■ Introduction
In React, all you do is build components. Then, you put components together
to make another component that depicts a complete view or page. A component
encapsulates the state of data and the view, or how it is rendered. This makes writing and
reasoning about the entire application easier, by splitting it into components and focusing
on one thing at a time.
Components talk to each other by sharing state information in the form of read-only
properties to their child components and by callbacks to their parent components. I’ll dig
deeper into this concept in a later chapter, but the gist of it is that components in React
are very cohesive, and the coupling with one another is minimal.
No Templates
Many web application frameworks rely on templates to automate the task of creating
repetitive HTML or DOM elements. The templating language in these frameworks is
something that the developer will have to learn and practice. Not in React.
React uses a full-featured programming language to construct repetitive or
conditional DOM elements. That language is none other than JavaScript. For example,
when you want to construct a table, you write a for(...) loop in JavaScript, or use the
map() function of an Array.
There is an intermediate language to represent a virtual DOM, and that is JSX, which
is very similar to HTML. It lets you create nested DOM elements in a familiar language
rather than hand-construct them using JavaScript functions. Note that JSX is not a
programming language; it is a representational markup like HTML. It’s also very similar
to HTML so you don’t have to learn too much. More about this later.
You don’t have to use JSX; you can write pure JavaScript to create your virtual DOM if
you prefer. But if you are used to HTML, it’s simpler to just use JSX. Don’t worry about it;
it’s really not a new language that you’ll need to learn.
Isomorphic
React can be run on the server too. That’s what isomorphic means: the same code can run
on both server and the browser.
This allows you to create pages on the server when required, for example, for SEO
purposes. The same code can be shared on the server to achieve this. On the server, you’ll
need something that can run JavaScript, and this is where I introduce Node.js.
Node.js
Simply put, Node.js is JavaScript outside of a browser. The creators of Node.js just took
Chrome’s V8 JavaScript engine and made it run independently as a JavaScript runtime. If
you are familiar with the Java runtime that runs Java programs, you can easily relate to the
JavaScript runtime: the Node.js runtime runs JavaScript programs.
7
Chapter 1 ■ Introduction
Node.js Modules
In a browser, you can load multiple JavaScript files, but you need an HTML page to do all
that. You cannot refer to another JavaScript file from one JavaScript file. But for Node.js,
there is no HTML page that starts it all. In the absence of the enclosing HTML page,
Node.js uses its own module system based on CommonJS to put together multiple
JavaScript files.
Modules are like libraries. You can include the functionality of another JavaScript file
(provided it’s written to follow a module’s specifications) by using the keyword require
(which you won’t find in a browser’s JavaScript). You can therefore split your code
into files or modules for the sake of better organization, and load one or another using
require. I’ll talk about the exact syntax in a later chapter; at this point it’s enough to note
that compared to JavaScript on the browser, there is a cleaner way to modularize your
code using Node.js.
Node.js ships with a bunch of core modules compiled into the binary. These
modules provide access to the operating system elements such as the file system,
networking, input/output, etc. They also provide some utility functions that are
commonly required by most programs.
Apart from your own files and the core modules, you can also find a great amount of
third-party open source libraries available for easy installation. This brings us to npm.
8
Chapter 1 ■ Introduction
Express
Node.js is just a runtime environment that can run JavaScript. To write a full-fledged
web server by hand on Node.js directly is not that easy, nor is it necessary. Express is the
framework that simplifies the task of writing your server code.
The Express framework lets you define routes, specifications of what to do when a
HTTP request matching a certain pattern arrives. The matching specification is regular
expression (regex) based and is very flexible, like most other web application frameworks.
The what-to-do part is just a function that is given the parsed HTTP request.
Express parses request URL, headers, and parameters for you. On the response side,
it has, as expected, all of the functionality required by web applications. This includes
setting response codes, setting cookies, sending custom headers, etc. Further, you can
write Express middleware, which are custom pieces of code that can be inserted in any
request/response processing path to achieve common functionality such as logging,
authentication, etc.
Express does not have a template engine built in, but it supports any template engine
of your choice such as pug, mustache, etc. But, for an SPA, you will not need to use a
9
Chapter 1 ■ Introduction
server-side template engine. This is because all dynamic content generation is done on
the client, and the web server only serves static files and data via API calls. Especially with
MERN stack, page generation is handled by React itself on the server side.
In summary, Express is a web server framework meant for Node.js, and it is not very
different from many other server-side frameworks in terms of what you can achieve with it.
MongoDB
MongoDB is the database used in the MERN stack. It is a NoSQL document-oriented
database, with a flexible schema and a JSON-based query language. I’ll discuss a few
things that MongoDB is (and is not) here.
NoSQL
NoSQL stands for “non-relational,” no matter what the acronym expands to. It’s
essentially not a conventional database where you have tables and columns (called a
relational database). I find that there are two attributes of NoSQL that differentiate it from
the conventional.
The first is the ability to horizontally scale by distributing the load over multiple
servers. NoSQL databases do this by sacrificing an important (for some) aspect of the
traditional databases: strong consistency. That is, the data is not necessarily consistent
for very brief amounts of time across replicas. For more information, read up on the
“CAP theorem” (https://en.wikipedia.org/wiki/CAP_theorem). But in reality, very few
applications require web scale, and this aspect of NoSQL databases comes into play very
rarely.
The second, and to me, more important, aspect is that NoSQL databases are
not necessarily relational databases. You don’t have to think of your data in terms of
rows and columns of tables. The difference in the representation in the application
and on disk is sometimes called impedance mismatch. This is a term borrowed from
electrical engineering, and it means, roughly, that we’re not talking the same language.
In MongoDB, instead, you can think of the persisted data just as you see it in your
application code; that is, as objects or documents. This helps a programmer avoid a
translation layer, whereby one has to convert or map the objects that the code deals
with to relational tables. Such translations are called object relational mapping (ORM)
layers.
Document-Oriented
Compared to relational databases where data is stored in the form of relations, or tables,
MongoDB is a document-oriented database. The unit of storage (comparable to a row) is
a document, or an object, and multiple documents are stored in collections (comparable
to a table). Every document in a collection has a unique identifier by which it can be
accessed. The identifier is indexed automatically.
10
Chapter 1 ■ Introduction
Imagine the storage structure of an invoice, with the customer name, address, etc.
and a list of items (lines) in the invoice. If you had to store this in a relational database,
you would use two tables, say, invoice and invoice_lines, with the lines or items
referring to the invoice via a foreign-key relation. Not so in MongoDB. You would store
the entire invoice as a single document, fetch it, and update it in an atomic operation.
This applies not just to line items in an invoice. The document can be any kind of deeply
nested object.
Modern relational databases have started supporting one level of nesting by
allowing array fields and JSON fields, but it is not the same as a true document database.
MongoDB has the ability to index on deeply nested fields, which relational databases
cannot do.
The downside is that the data is stored denormalized. This means that data is
sometimes duplicated, requiring more storage space. Also, things like renaming a master
(catalog) entry name would mean sweeping through the database. But then, storage has
become relatively cheap these days, and renaming master entries are rare operations.
Schema-Less
Storing an object in a MongoDB database does not have to follow a prescribed schema.
All documents in a collection need not have the same set of fields.
This means that, especially during early stages of development, you don’t need to
add/rename columns in the schema. You can quickly add fields in your application code
without having to worry about database migration scripts. At first, this may seem a boon,
but in effect all it does is transfer the responsibility of data sanity from the database to
your application code. I find that in larger teams and more stable products, it is better
to have a strict or semi-strict schema. Using object document mapping libraries such as
mongoose (not covered in this book) alleviates this problem.
JavaScript Based
MongoDB’s language is JavaScript.
For relational databases, there is a query language called SQL. For MongoDB, the
query language is based on JSON: you create, search for, make changes, and delete
documents by specifying the operation in a JSON object. The query language is not
English-like (you don’t SELECT or say WHERE), and therefore much easier to construct
programmatically.
Data is also interchanged in JSON format. In fact, the data is natively stored in a
variation of JSON called BSON (where B stands for Binary) in order to efficiently utilize
space. When you retrieve a document from a collection, it is returned as a JSON object.
MongoDB comes with a shell that is built on top of a JavaScript runtime like Node.js.
This means that you have a powerful and familiar scripting language (JavaScript)
to interact with the database via command line. You can also write code snippets in
JavaScript that can be saved and run on the server (the equivalent of stored procedures).
11
Chapter 1 ■ Introduction
React-Router
React supplies only the view rendering capability and helps manage interactions in
a single component. When it comes to transitioning between different views of the
component and keeping the browser URL in sync with the current state of the view, we
need something more.
This capability of managing URLs and history is called routing. It is similar to the
server-side routing that Express does: a URL is parsed, and based on its components,
a piece of code is associated with the URL. React-Router not only does this, but also
manages the browser’s Back button functionality so that we can transition between what
seem as pages without loading the entire page from the server. We could have built this
ourselves, but React-Router is a very easy-to-use library that manages this for us.
React-Bootstrap
Bootstrap, the most popular CSS framework, has been adapted to React and the project is
called React-Bootstrap. This library not only gives us most of the Bootstrap functionality,
but the components and widgets provided by this library also give us a wealth of
information on how to design our own widgets and components.
There are other component/CSS libraries built for React (such as Material-UI, MUI,
Elemental UI, etc.) and also individual components (such as react-select, react-treeview,
and react-date-picker). All these are good choices too, depending on what you are trying
to achieve. But I have found that React-Bootstrap is the most comprehensive single
library with the familiarity of Bootstrap (which I presume most of you know already).
Webpack
Webpack is indispensable when it comes to modularizing code. There are other
competing tools such as Bower and Browserify which also serve the purpose of
modularizing and bundling all the client code, but I found that webpack is easier to use
and does not require another tool (like gulp or grunt) to manage the build process.
We will be using webpack not just to modularize and build the client-side code into a
bundle to deliver to the browser, but also to “compile” some code. The compilation step is
needed to generate pure JavaScript from React code written in JSX.
12
Chapter 1 ■ Introduction
Other Libraries
Very often, there’s a need for a library to address a common problem. In this book, we’ll
use body-parser (to parse POST data in the form of JSON, or form data), ESlint (for
ensuring that the code follows conventions), and express-session, all on the server side,
and some more like react-select on the client side.
Why MERN?
So now you have a fair idea of the MERN stack and what it is based on. But is it really far
superior to any other stack, say, LAMP, MEAN, J2EE, etc.? By all means, all of these stacks
are good enough for most modern web applications. All said and done, familiarity is the
crux of productivity in software, so I wouldn’t advise a MERN beginner to blindly start
their new project on MERN, especially if they have an aggressive deadline. I’d advise them
to choose the stack that they are already familiar with.
But MERN does have its special place. It is ideally suited for web applications that
have a large amount of interactivity built into the front-end. Go back and reread the
section on “Why Facebook built React.” It will give you some insights. You could perhaps
achieve the same with other stacks, but you’ll find that it is most convenient to do so with
MERN. So, if you do have a choice of stacks, and the luxury of a little time to get familiar,
you may find that MERN is a good choice. I’ll talk about a few things that I like about
MERN, which may help you decide.
JavaScript Everywhere
The best part about MERN is that there is a single language used everywhere. It uses
JavaScript for client-side code as well as server-side code. Even if you have database
scripts (in MongoDB), you write them in JavaScript. So, the only language you need to
know and be comfortable with is JavaScript.
This is kind of true of all other stacks based on MongoDB and Node.js, especially
the MEAN stack. But what makes the MERN stack stand out is that you don’t even need
a template language to generate pages. In the React way, you programmatically generate
HTML (actually DOM elements) using JavaScript. So, not only do you avoid learning a
new language, you also get the full power of JavaScript. This is in contrast to a template
language, which will have its own limitations. Of course, you will need to know HTML
and CSS, but these are not programming languages, and there is no way you can avoid
learning HTML and CSS (not just the markup, but the paradigm and the structure).
Apart from the obvious advantage of not having to switch contexts while writing
client-side and server-side code, having a single language across tiers also lets you share
code between them. I can think of functions that execute business logic, do validation,
etc. that can be shared. They need to be run on the client side so that user experience is
better by being more responsive to user inputs. They also need to be run on the server
side to protect the data model.
13
Chapter 1 ■ Introduction
JSON Everywhere
When using the MERN stack, object representation is JSON (JavaScript Object Notation)
everywhere: in the database, in the application server, and on the client, and even on the
wire.
I have found that this often saves me a lot of hassle in terms of transformations. No
object relational mapping (ORM), no having to force fit an object model into rows and
columns, no special serializing and de-serializing code. An object document mapper
(ODM) such as mongoose may help enforce a schema and make things even simpler, but
the bottom line is that you save a lot of data transformation code.
Further, it just lets me think in terms of native objects, and see them as their natural
selves even when inspecting the database directly using a shell.
Node.js Performance
Due to its event-driven architecture and non-blocking I/O, the claim is that Node.js is
very fast and a resilient web server.
Although it takes a little getting used to, I have no doubt that when your application
starts scaling and receiving a lot of traffic, this will play an important role in cutting
costs as well as savings in terms of time spent in trouble-shooting server CPU and I/O
problems.
Isomorphic
SPAs used to have the problem that they were not SEO friendly. We had to use
workarounds like running PhantomJS on the server to pseudo-generate HTML pages,
or use Prerender.io services that did the same for us. This introduced an additional
complexity.
With the MERN stack, serving pages out of the server is natural and doesn’t require
tools that are after-thoughts. This is made possible due to the virtual DOM technique
used by React. Once you have a virtual DOM, the layer that translates it to a renderable
page can be abstracted. For the browser, it is the real DOM. For the server side, it is
HTML. In fact, React Native has taken it to another extreme: it can even be a mobile app!
I don’t cover React Native in this book, but this should give you a feel of what virtual
DOM can do for you in future.
14
Random documents with unrelated
content Scribd suggests to you:
The occasions which called the Signal Corps into activity were
various, but they were most frequently employed in reporting the
movements of troops, sometimes of the Union, sometimes of the
enemy. They took post on elevated stations, whether a hill, a tall
tree, or the top of a building. Any position from which they could
command a broad view of the surrounding country was occupied for
their purpose. If nature did not always provide a suitable place for
lookout, art came to the rescue, and signal towers of considerable
height were built for this class of workers, who, like the cavalry, were
the “eyes” of the army if not the ears. I remember several of these
towers which stood before Petersburg in 1864. They were of
especial use there in observing the movements of troops within the
enemy’s lines, as they stood, I should judge, from one hundred to
one hundred and fifty feet high. Although these towers were erected
somewhat to the rear of the Union main lines, and were a very open
trestling, they were yet a conspicuous target for the enemy’s long-
range guns and mortar-shells.
Sometimes the nerve of the flagman was put to a very severe test,
as he stood on the summit of one of these frail structures waving his
flag, his situation too like that of Mahomet’s coffin, while the
Whitworth bolts whistled sociably by him, saying, “Where is he?
Where is he?” or, by another interpretation, “Which one? Which
one?” Had one of these bolts hit a corner post of the lookout, the
chances for the flagman and his lieutenant to reach the earth by a
new route would have been favorable, although the engineers who
built them claimed that with three posts cut away the tower would still
stand. But, as a matter of fact, I believe no shot ever seriously
injured one of the towers, though tons weight of iron must have been
hurled at them. The roof of the Avery House, before Petersburg, was
used for a signal station, and the shells of the enemy’s guns often
tore through below much to the alarm of the signal men above.
Signalling was carried on during an engagement between different
parts of the army. By calling for needed re-enforcements, or giving
news of their approach, or requesting ammunition, or reporting
movements of the enemy, or noting the effects of shelling,—in these
and a hundred kindred ways the corps made their services
invaluable to the troops.
Sometimes signal officers on
shore communicated with
others on shipboard, and, in
one instance, Lieutenant
Brown told me that through the
information he imparted to a
gunboat off Suffolk, in 1863,
regarding the effects of the
shot which were thrown from it,
General Longstreet had since
written him that the fire was so
accurate he was compelled to
withdraw his troops. The
signals were made from the
tower of the Masonic Hall in
Suffolk, whence they were
taken up by another signal
party on the river bluff, and
thence communicated to the
gunboat.
Not long since, General
Sherman, in conversation,
SIGNAL TREE-TOP.
alluded to a correspondent of
the New York “Herald” whom
he had threatened to hang,
declaring that had he done so his “death would have saved ten
thousand lives.” The relation of this anecdote brings out another
interesting phase of signal-corps operations. It seems that one of our
signal officers had succeeded in reading the signal code of the
enemy, and had communicated the same to his fellow-officers. With
this code in their possession, the corps was enabled to furnish
valuable information directly from Rebel headquarters, by reading
the Rebel signals, continuing to do so during the Chattanooga and
much of the Atlanta campaign, when the enemy’s signal flags were
often plainly visible. Suddenly this source of information was
completely cut off by the ambition of the correspondent to publish all
the news, and the
natural result was the
enemy changed the
code. This took place
just before Sherman’s
attack on Kenesaw
Mountain (June, 1864),
and it is to the hundreds
slaughtered there that
he probably refers.
General Thomas was
ordered to arrest the
reporter, and have him
hanged as a spy; but
old “Pap” Thomas’ kind
heart banished him to
the north of the Ohio for
the remainder of the
war, instead.
When Sherman’s
headquarters were at
Big Shanty, there was a
signal station located in
A SIGNAL TOWER BEFORE PETERSBURG, VA.
his rear, on the roof of
an old gin-house, and
this signal officer,
having the “key” to the enemy’s signals, reported to Sherman that he
had translated this signal from Pine Mountain to Marietta,—“Send an
ambulance for General Polk’s body,”—which was the first tidings
received by our army that the fighting bishop had been slain. He was
hit by a shell from a volley of artillery fired by order of General
Sherman.
To the men in the other arms of the service, who saw this
mysterious and almost continuous waving of flags, it seemed as if
every motion was fraught with momentous import. “What could it all
be about?” they would ask one another. A signal station was located,
in ’61-2, on the top of what was known as the Town Hall (since
burned) in Poolesville, Md., within a few rods of my company’s
camp, and, to the best of my recollection, not an hour of daylight
passed without more or less flag-waving from that point. This
particular squad of men did not seem at all fraternal, but kept aloof,
as if (so we thought) they feared they might, in an unguarded
moment, impart some of the important secret information which had
been received by them from the station at Sugar Loaf Mountain or
Seneca. Since the war, I have learned that their apparently excited
and energetic performances were, for the most part, only practice
between stations for the purpose of acquiring familiarity with the
code, and facility in using it.
It may be thought that the duties of the Signal Corps were always
performed in positions where their personal safety was never
imperilled. But such was far from the fact. At the battle of Atlanta,
July 22, 1864, a signal officer had climbed a tall pine-tree, for the
purpose of directing the fire of a section of Union artillery, which was
stationed at its foot, the country being so wooded and broken that
the artillerists could not certainly see the position of the enemy. The
officer had nailed a succession of cleats up the trunk, and was on
the platform which he had made in the top of the tree, acting as
signal officer, when the Rebels made a charge, capturing the two
guns, and shot the officer dead at his post.
During the battle of Gettysburg, or, at least, while Sickles was
contending at the Peach Orchard against odds, the signal men had
their flags flying from Little Round Top; but when the day was lost,
and Hood with his Texans pressed towards that important point, the
signal officers folded their flags, and prepared to visit other and less
dangerous scenes. At that moment, however, General Warren of the
Fifth Corps appeared, and ordered them to keep their signals waving
as if a host were immediately behind them, which they did.
From the important nature of the duties which they performed, the
enemy could not look upon them with very tender regard, and this
fact they made apparent on every opportunity. Here is an incident
which, I think, has never been published:—
When General Nelson’s division arrived at Shiloh, Lieutenant
Joseph Hinson, commanding the Signal Corps attached to it,
crossed the Tennessee and reported to General Buell, after which he
established a station on that side of the river, from which messages
were sent having reference to the disposition of Nelson’s troops. The
crowd of stragglers (presumably from Grant’s army) was so great as
to continually obstruct his view, and in consequence he pressed into
service a guard from among the stragglers themselves to keep his
view clear, and placed his associate, Lieutenant Hart, in charge.
Presently General Grant himself came riding up the bank, and, as
luck would have it, came into Lieutenant Hinson’s line of vision.
Catching sight of a cavalry boot, without stopping to see who was in
it, in his impatience, Lieutenant Hart sang out: “Git out of the way
there! Ain’t you got no sense?” Whereupon Grant very quietly
apologized for his carelessness, and rode over to the side of General
Buell. When the lieutenant found he had been addressing or
“dressing” a major-general, his confusion can be imagined. (See
frontispiece).
One more incident illustrating the utility of signalling will close the
chapter:—
After arriving before Fort McAllister, General Sherman sent
General Hazen down the right bank of the Ogeechee to take the fort
by assault, and himself rode down the left bank to a rice plantation,
where General Howard had established a signal station to overlook
the river and watch for vessels. The station was built on the top of a
rice-mill. From this point the fort was visible, three miles away. In due
time a commotion in the fort indicated the approach of Hazen’s
troops, and the signal officer discovered a signal flag about three
miles above the fort, which he found was Hazen’s, the latter inquiring
if Sherman was there. He was answered affirmatively, and informed
that Sherman expected the fort to be carried before night. Finally
Hazen signalled that he was ready, and was told to go ahead.
Meanwhile, a small United States steamer had been descried
coming up the river, and, noticing the party at the rice-mill, the
following dialogue between signal flags ensued:—
“Who are you?”
“General Sherman.”
“Is Fort McAllister taken?”
“Not yet; but it will be in a minute.”
And in a few minutes it was taken, and the fact signalled to the
naval officers on the boat, who were not in sight of the fort.
*** END OF THE PROJECT GUTENBERG EBOOK HARDTACK
AND COFFEE ***
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com