Beginning Node.js, Express MongoDB Development (Greg Lim) (Z-Library)

Author: Greg Lim

技术

No Description

📄 File Format: PDF
💾 File Size: 5.0 MB
44
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
Beginning Node.js, Express & MongoDB Development Greg Lim Copyright © 2019 Greg Lim All rights reserved. COPYRIGHT © 2019 BY GREG LIM ALL RIGHTS RESERVED. NO PART OF THIS BOOK MAY BE REPRODUCED IN ANY FORM OR BY ANY ELECTRONIC OR MECHANICAL MEANS INCLUDING INFORMATION STORAGE AND RETRIEVAL SYSTEMS, WITHOUT PERMISSION IN WRITING FROM THE AUTHOR. THE ONLY EXCEPTION IS BY A REVIEWER, WHO MAY QUOTE SHORT EXCERPTS IN A REVIEW.
📄 Page 3
FIRST EDITION: JULY 2019
📄 Page 4
Table of Contents PREFACE CHAPTER 1: INTRODUCTION CHAPTER 2: INTRODUCTION TO NPM & EXPRESS CHAPTER 3: BEGINNING OUR BLOG PROJECT CHAPTER 4: TEMPLATING ENGINES CHAPTER 5: INTRODUCTION TO MONGODB CHAPTER 6: APPLYING MONGODB TO OUR PROJECT CHAPTER 7: UPLOADING AN IMAGE WITH EXPRESS CHAPTER 8: INTRODUCTION TO EXPRESS MIDDLEWARE CHAPTER 9: REFACTORING TO MVC CHAPTER 10: USER REGISTRATION CHAPTER 11: USER AUTHENTICATION WITH EXPRESS SESSIONS CHAPTER 12: SHOWING VALIDATION ERRORS CHAPTER 13: RELATING POST COLLECTION WITH USER COLLECTION CHAPTER 14: ADDING A WYSIWYG EDITOR CHAPTER 15: USING MONGODB ATLAS CHAPTER 16: DEPLOYING WEB APPS ON HEROKU ABOUT THE AUTHOR
📄 Page 5
PREFACE About this book In this book, we take you on a fun, hands-on and pragmatic journey to learning Node.js, Express and MongoDB development. You'll start building your first Node.js app within minutes. Every chapter is written in a bite-sized manner and straight to the point as I don’t want to waste your time (and most certainly mine) on the content you don't need. In the end, you will have the skills to create a blog app and deploy it to the Internet. In the course of this book, we will cover: - Chapter 1: Introduction - Chapter 2: Introduction to npm & Express - Chapter 3: Beginning our Blog Project - Chapter 4: Templating Engines - Chapter 5: Introduction to MongoDB - Chapter 6: Applying MongoDB to our Project - Chapter 7: Uploading an Image with Express - Chapter 8: Introduction to Express Middleware - Chapter 9: Refactoring to MVC - Chapter 10: User Registration - Chapter 11: User Authentication with Express Sessions - Chapter 12: Showing Validation Errors - Chapter 13: Relating Post Collection with User Collection - Chapter 14: Adding a WYSIWYG Editor - Chapter 15: Using MongoDB Atlas - Chapter 16: Deploying Web Apps on Heroku The goal of this book is to teach you Node.js, Express and MongoDB development in a manageable way without overwhelming you. We focus only on the essentials and cover the material in a hands-on practice manner for you to code along. Working Through This Book
📄 Page 6
This book is purposely broken down into sixteen short chapters where the development process of each chapter will center on different essential topics. The book takes a practical hands on approach to learning through practice. You learn best when you code along with the examples in the book. Along the way, if you encounter any problems, do drop me a mail at support@i- ducate.com where I will try to answer your query. Requirements No previous knowledge on Node.js development required, but you should have basic programming knowledge. Getting Book Updates To receive updated versions of the book, subscribe to our mailing list by sending a mail to support@i-ducate.com. I try to update my books to use the latest version of software, libraries and will update the codes/content in this book. So, do subscribe to my list to receive updated copies! Code Examples Where necessary, the relevant source codes links are posted at the end of each chapter.
📄 Page 7
CHAPTER 1: INTRODUCTION Node.js is one of the most popular server-side frameworks. Increasing companies are building their applications with Node.js for example, Wal- Mart, LinkedIn, PayPal, YouTube, Yahoo!, Amazon.com, Netflix, eBay and Reddit. In this book, we will learn about Node.js together with Express and MongoDB and build a blog app from scratch with them. In the process, you will progress from a beginner to where you can build apps effectively using these technologies. You will learn a range of topics like user authentication, data validation, asynchronous JavaScript, password hashing, Express, MongoDB, templating engines, maintaining user sessions and more. The App We Will Be Building We will build a blog app which lets users write blog entries once they sign up with an account (fig. 1.1, 1.2, 1.3). Figure 1.1 – Home Page
📄 Page 8
Figure 1.2 – Register a User Figure 1.3 – Create Blog Post Form After the user registers, she can go to the homepage and login with her credentials. The navigation bar will dynamically show different items depending on the user being logged in or out. We will achieve this using the EJS templating engine. Once logged in, the navigation bar will have a ‘ Log
📄 Page 9
Out ’ item. There will also be a ‘ New Post ’ item where the user can create a new blog post and upload an associated image file. When she goes back to the Home page, her blog entries will be posted there with the username and date posted. Throughout this app, we will learn a lot of concepts and solidify our Node.js, Express and MongoDB knowledge. What is Node.js? Before we understand what Node.js is, we need to understand how the Internet works. When a user opens up her browser and makes a request to a site, she is known as a client. The client makes a request of a certain website to a server which upon receiving the request, responds with the content of the requested site to the client who then displays it in her browser. For example, I make a request to amazon.com and Amazon servers responds back with the HTML for amazon.com. There have been server-side programming languages like PHP, Ruby, Python, ASP, Java and others which helps us respond to browser requests appropriately on the server. Traditionally, JavaScript is used to run only on the browser to provide website interactivity for example dropdown menus. But in 2009, Node.js took V8, Google Chrome ’ s powerful JavaScript engine, out of the browser and enabled it to run on servers. Thus, in addition to the existing server-side languages, developers could now choose JavaScript to develop server-side applications. What benefits does choosing Node.js as a server-side language bring about? - Firstly, the V8 JavaScript engine used in Google Chrome is fast and can execute thousands of instructions a second - Secondly, Node.js encourages an asynchronous coding style making for faster code to manage concurrency while avoiding multithreaded problems. - Thirdly, because of its popularity, JavaScript offers Node.js access to many useful libraries - And of course, Node.js provides us the ability to share code between browser and server since they both use JavaScript code. Based on this, developers have created the MEAN stack, an all-JavaScript web application stack consisting of MongoDB (a database controlled by JavaScript) , Express, Angular (a front-end JavaScript framework – I
📄 Page 10
have in fact written a book entirely on Angular) and Node.js. Using JavaScript everywhere is a major benefit of Node.js. In fact, there is also a MERN stack where instead of using Angular, React is used as the front end. In this book, we will cover MongoDB, Express and Node.js, i.e. the MEN stack. Installing Node.js To install Node.js, go to nodejs.org (fig. 1.4) and download the appropriate version for your Operating System. Figure 1.4 Installation should be straightforward. Once Node.js has been installed, go to your Terminal and run: node -v This shows the version of Node that you installed e.g. v10.15.3 (at time of this book ’ s writing). You should also be able to run: npm -v which shows the version of npm installed e.g. 6.4.1. We will revisit npm later in this book. Creating our First Server
📄 Page 11
We will create our first server to better understand how a request and respond between a client and a server works. In a code editor of your choice, (I will be using Visual Studio Code in this book), choose a directory location and in it, create a new file called index.js. Fill in the below code to create our first server: const http = require('http') const server = http.createServer((req, res) =>{ console.log(req.url) res.end('Hello Node.js') }) server.listen(3000) Code Explanation const http = require('http') The require function in Node.js helps us to grab the package in Node.js called http. require is similar to import or include in other languages. require takes the name of a package as a string argument and returns the package. We require the http package and assign it to a variable called http. You can then use http as you would any object. The general convention is that when you require a module, you put it in a variable that has the same name as the module itself. In our example, we put the http module in a variable of the same name http. You can of course choose to put it in a variable with a different name, there ’ s nothing enforcing that in code, but it does prevent confusion. http is one of the built-in packages that Node.js provides to perform actions on the server. Other essential built-in packages that we will cover later is the filesystem access (fs) package and the utility function (util) package. const server = http.createServer(…) Next, we create and start a server with the createServer method from http package. createServer takes in a function as parameter: const server = http.createServer((req, res) =>{ console.log(req.url) res.end('Hello Node.js') })
📄 Page 12
The function provided to createServer is called a callback function. It will be called when the createServer function is completed. When it is called, it will be provided the request (req – request from browser) and response (res – response to give back to browser) object in the function. We can do whatever we want with the two objects in the body of the function. In our case, we simply log the request url and after that respond with the text ‘ Hello Node.js ’ in the function body. server.listen(3000) Finally, with server.listen(3000) we start our server to start taking requests. That is, the server listens on port 3000 for requests. You can specify any port you want, it doesn ’ t have to be 3000. If you are asking what is a port? A port is a specific gateway on the server to host a particular app. For example, if there are multiple apps running on the same server, we specify different port numbers for different apps. Running index.js In our case, for any request made to port 3000, we respond with ‘ Hello Node.js ’ . To execute the file and start running the server, in Terminal, cd to the directory the file is located in and run: node index.js Now go to your browser and enter http://localhost:3000/. localhost in this case refers to our computer which is acting as a local server. But suppose the server is hosted on another computer or site, you can imagine that the link would be http://<computer ip>:3000/. In the last chapter of this book, we will learn how to deploy our app on to an external server Heroku to make our app available across the Internet. In your browser, you should see the text ‘ Hello Node.js ’ displayed in your browser (fig. 1.5). Figure 1.5 This is because we have responded to the request with the code res.end('Hello Node.js').
📄 Page 13
If you look at your Terminal running Node.js, you can see ‘ / ’ being logged. This is because we have the code console.log(req.url) which logs the request url. If you enter http://localhost:3000/noderocks, ‘ /noderocks ’ will be logged in the Terminal. So, you see that the req object contains request data from the browser. We now have a successful request and respond cycle and I hope that this serves as an example to better understand how a request and respond works between a client and a server. More on Request and Response Our app currently responds only with ‘ Hello Node.js ’ regardless of the url entered after localhost:3000. To have different responses based on different URLs, add the following code in bold: const http = require('http') const server = http.createServer((req, res) =>{ if(req.url === '/about') res.end('The about page') else if(req.url === '/contact') res.end('The contact page') else if(req.url === '/') res.end('The home page') else { res.writeHead(404) res.end('page not found') } }) server.listen(3000) To run the newly added code, we have to stop and restart the server with node index.js. Code Explanation Using an if-else statement in the callback function, we check for the request url and depending on its path, we response with different messages. If the url contains ‘ /about ’ , we serve the about page. If it contains ‘ /contact ’ , we serve the contact page and if it ’ s just ‘ / ’ , we serve the home page. If the path does not exist in the if-else, we default to the last else clause and respond with ‘ page not found ’ and also writeHead(404).
📄 Page 14
writeHead writes the status code of the request. Normally, a status code of 200 indicates that the server responded with a successful response. You can see the status code of your request whenever you request a site from the Chrome browser by going to ‘ Developer Tools under ‘ View ’ , ‘ Developer ’ , ‘ Developer Tools ’ (fig. 1.6). Figure 1.6 To see your request information, in ‘ Developer Tools ’ , click on ‘ Network ’ . Under ‘ Status ’ , it will show the status code. In figure 1.7, I have requested for ‘ /contact ’ url, a valid path which returns status code 200 indication ‘ OK ’ . Figure 1.7 If I request for an invalid url like ‘ /contacts ’ (with an extra ‘ s ’ ), it returns the code 404 indicating ‘ Not Found ’ (fig. 1.8).
📄 Page 15
Figure 1.8 With this, we have a way of handling different requests from a client and sending the appropriate response from the server. Responding with HTML We have been responding to requests with static text. In a real-world setting, we want to respond with HTML. We illustrate how to do so in this section. In the same folder as index.js, create a new file called index.html with the below simple HTML: <h1>Home Page</h1> Do the same for about.html( <h1>About Page</h1> ), contact.html( <h1>Contact Page</h1> ) and notfound.html( <h1>Page Not Found</h1> ). Back in index.js, add the below code in bold: const http = require('http') const fs = require('fs') const homePage = fs.readFileSync('index.html') const aboutPage = fs.readFileSync('about.html') const contactPage = fs.readFileSync('contact.html') const notFoundPage = fs.readFileSync('notfound.html') const server = http.createServer((req, res) =>{ if(req.url === '/about') res.end(aboutPage) else if(req.url === '/contact') res.end(contactPage) else if(req.url === '/') res.end(homePage)
📄 Page 16
else { res.writeHead(404) res.end(notFoundPage) } }) server.listen(3000) Code Explanation const fs = require('fs') We import a file system module ‘ fs ’ which helps us interact with files on our server. const homePage = fs.readFileSync('index.html') const aboutPage = fs.readFileSync('about.html') const contactPage = fs.readFileSync('contact.html') const notFoundPage = fs.readFileSync('notfound.html') The readFileSync method from fs reads the content of each file and returns it. We store the content in a variable for each page. const server = http.createServer((req, res) =>{ if(req.url === '/about') res.end(aboutPage) else if(req.url === '/contact') res.end(contactPage) else if(req.url === '/') res.end(homePage) else { res.writeHead(404) res.end(notFoundPage) } }) Instead of res.end() containing a static text, res.end now contains the HTML page variable. Running your App Re-start the server with node index.js and we will have HTML presented instead (fig. 1.9). And that is how we respond to requests with HTML using the filesystem module.
📄 Page 17
Figure 1.9 Notice that we have been writing a single JavaScript function for our entire application: … const server = http.createServer((req, res) =>{ if(req.url === '/about') res.end(aboutPage) else if(req.url === '/contact') res.end(contactPage) else if(req.url === '/') res.end(homePage) else { res.writeHead(404) res.end(notFoundPage) } }) … This single function listens to a web browser ’ s requests, either from a computer. mobile phone or any other client consuming our API. We call this function a request handler. When a request comes in, this function looks at the request and decides how to respond. It takes two arguments, an object that represents the request (req) and an object that represents the response (res). Every Node.js application is just like this, a single request handler function responding to requests. For small sites, this might seem easy, but things quickly get huge and unmanageable quickly as you can imagine, for example a site like Amazon.com which includes rendering dynamic reusable HTML templates, rendering/uploading of images etc. We explore in the next chapter how Express helps to solve this problem and make it easier for us to write web applications with Node.js. Summary In this book, we will build a blog app with Node.js, Express and MongoDB.
📄 Page 18
Node.js allow us to use JavaScript as a server-side programming language which gives us advantages like fast execution and being able to share code between the server and client. We understood how a request and respond cycle between a client and server works by coding and starting up a simple server example. We handled requests and responded appropriately with both text and HTML.
📄 Page 19
CHAPTER 2: INTRODUCTION TO NPM & EXPRESS Installing Custom Packages with npm In our app from chapter one, we imported packages from Node.js itself e.g., http, fs. Now the Node.js community have lots of developers who write custom modules/packages that we can use in our own apps. These packages are hosted on a site called npmjs.com (fig. 2.1) where you can search to see which is appropriate to use in your own code. We use npm (or Node Package Manager) to manage the packages that we download. npm is an official helper for Node projects that comes along with Node when we installed it. Figure 2.1 One very important custom package we will install is Express. Because vanilla Node.js APIs can be verbose, confusing and limited in features, Express is a framework that acts as a light layer atop the Node.js web server making it easier to develop Node.js web applications. Express is used by many companies. We will see later how it simplifies the APIs of Node.js,
📄 Page 20
adds helpful features, helps organizes our application ’ s functionality with middleware and routing, adds helpful utilities to Node.js ’ s HTTP objects and facilitates rendering of dynamic HTML views. In the course of this book, we will explore these features in depth. So, go to npmjs.com and search for ‘ express ’ , there will be instructions on how to install and use the express package (fig. 2.2). Figure 2.2 As mentioned in the site under ‘ Installation ’ , we have to run npm install express to install the express package. Before we run npm install express, npm requires that we have a file package.json to track all packages and their versions used in our app. If you run npm install express now without the file, you will get a series of warnings like “ no such file or directory, open … package.json ” . To generate package.json file, run ‘ npm init ’ which will prompt a series of
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List