Nodel
Nodel
Nodel
js API
Edition: I – February 10, 2020
Genre: Software, Web Development
Publisher: Learning Curve Books
Imprint: Independently published
ISBN: 9798612518297
Author: Greg Sidelnikov ([email protected])
Editors, volunteers, contributors: Grace Neufeld.
1 bash.exe 1
1.0.1 What is bash.exe? . . . . . . . . . . . . . . . . . . . . . 2
1.0.2 Ubuntu on Windows? . . . . . . . . . . . . . . . . . . . 3
1.1 Migrating From Apache to Node . . . . . . . . . . . . . . . . . 4
1.2 Node Libraries and Frameworks . . . . . . . . . . . . . . . . . . 4
1.3 Running Node Server . . . . . . . . . . . . . . . . . . . . . . . 5
2 Installation 7
2.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1 apt install nodejs . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 Installing Node on Windows . . . . . . . . . . . . . . . . . . . . 9
2.4 Configuring Node Server Globally . . . . . . . . . . . . . . . . . 11
2.5 Enable Node To Run From Any Directory . . . . . . . . . . . . . 13
2.6 Exit from Node . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.7 Congratulations! . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3 Running Applications 17
NODE.JS
What Is A Server?
Just like a server at a restaurant serving a meal, a computer server is something
that serves files over the network via a dedicated IP address.
For many people server setup and configuration are some of the least exciting parts
about being a software developer.
To those who have propensity toward back-end development, it might be the holy
grail of how the application actually works.
To front-end developers, it’s a black box that generates console errors.
If you want to work for a start-up company as a back-end engineer, having deep
knowledge of how servers work is required experience. But even if you are a front-
end developer, knowing how to set up a server will expand your skill set and might
increase chances of getting a Full Stack developer job.
Today it is not uncommon for front-end developers to know how to work with
servers. You’re only gaining if you learn how to set up your own server.
I also think that servers can be exciting for those with entrepreneurial mindset –
it gives you the power to build your own custom applications. Nothing is more
thrilling than having ability to launch the child of your imagination into the world.
Node Server
Setting up a Node server can be broken into three parts: 1] installation, 2]
adding modules and other dependencies using a manifest file, and 3] writing the
minimum required code in main index.js file to launch and run the server.
We will also write our own api.js module responsible for registering users and
authenticating HTTP requests – in order to read from and write to a database.
This enables you to make virtually any application you can think of.
This book contains examples you can simply copy and paste into Terminal on Mac
or cmd.exe on Windows (or bash.exe on Windows 10,) but your are encouraged
to type them manually. It’s the only way to get better at the command line –
the skill that makes you a much more productive software developer.
You might need to get a web host to deploy your server online but the process is the
same on localhost as it is elsewhere. It’s just the hosted solution will additionally
route your server’s localhost environment to your browser via IP address.
Chapter 1
bash.exe
Did you know that starting with Windows 10 you can work in Linux-like bash
environment directly from your Windows computer?
It can be enabled in Windows 10 Control Panel:
1
2 CHAPTER 1. BASH.EXE
You can run Linux-based commands on a Windows file system this way.
In this book we will explore installing Node on Mac, Windows and Linux.
It wouldn’t be fair to show console examples for one operating system only. The
chapters will interchange between Windows bash.exe and Terminal on the Mac.
Commands like npm install package name (to install a node package with Node
Package Manager) or node index.js (to run index.js on Node server) are the same
on all operating systems.
Ubuntu for Windows is free. Simply find it in Windows store and download
it. Follow simple instructions to finish installation. Congrats! You can now use
Ubuntu commands on your Windows 10 bash.exe. Can you use another Linux
distribution such as Debian? Sure! Just look for it in Microsoft store. You can
even set it up so that you can run multiple distribution on the same Windows
computer.
4 CHAPTER 1. BASH.EXE
Installation
There are 3 things you should worry about when installing a Node server:
1. Choosing to install Node globally on your Operating System or making it local
to a project directory on your hard drive.
2. Configuring package.json manifest file – it is automatically created by Node
installation, but it’s nice to know how it actually works, so we’ll break it down.
3. Understanding node modules – the default directory where all Node modules
are downloaded when you install them from command line.
If you can understand these 3 key things about Node server, you’re making a huge
step toward getting better at back-end development with JavaScript. We’ll take
a look at each one as we move forward.
Local vs Production Development Environment
You can think of setting up Node as being synonymous with setting up your
development environment. Once you learn how to run the server on localhost,
it can then be deployed to a remote IP address and and ran on actual domain
name for your application. Do not develop directly on production server. If you’ve
never been employed as a software developer, you will probably want to avoid
developing that habit. In work environment all software is developed locally first
and committed to a decentralized version control system such as GitHub. It goes
without saying that your code should be able to work without bugs on localhost
before it is pushed to the production server.
7
8 CHAPTER 2. INSTALLATION
2.1 Mac
You might want to start learning how to install programs from the command line.
Mac & Linux may have different program installation managers. On OSX you
generally use brew, yum or port (See macports.org) command. On Linux it’s
either apt-get or more commonly just apt. Your should probably use apt.
The reason for so many ways to install packages on Linux-based OS’es is due to
many open-source distributions (Debian, Ubuntu, Fedora, Arch, CentOS...etc.,)
each in own unique flavor and version history.
Technically, you can also use apt on Mac OSX, if it’s available. (It should be.)
If you already have apt but you want brew – which some find to be better – on
your OSX, run apt install linuxbrew-wrapper
Now you can use brew to install packages such as nodejs, for example:
Just run brew install nodejs to install Node in Terminal on OSX.
To do the same on Linux use apt-get install nodejs in bash.
Or simply apt install nodejs in bash. There are minor differences between apt
and apt-get, you can use either one. But apt is considered better.
You can also try apt install nodejs in bash. And this is my preferred way.
2.2 Windows
Some older laptops or PCs might still be 32 bit. So, if you’re not sure, run the
following command in the cmd window: wmic os get osarchitecture
10 CHAPTER 2. INSTALLATION
Just choose Window Installer and 32-bit or 64-bit version. I chose 64-bit one,
because my computer is 64-bit. Yours is too, most likely.
Figure 2.3: Click on the downloaded file (I’m using Chrome browser here.)
This will begin the Windows installation process. Just click Next everywhere.
2.4. CONFIGURING NODE SERVER GLOBALLY 11
Wrong.
We still can’t launch node globally.
12 CHAPTER 2. INSTALLATION
In order to run the node command, you have to be in the directory in which Node
was installed, because that’s where node.exe executable file is.
Earlier we installed node into C:\Program Files\nodejs
Navigate to that directory by typing: cd C:\Program Files\nodejs
This means that we can launch node and execute JavaScript code. You can
feed node an index.js file to execute, instead of typing the code live in the cmd
program. We’ll take a look at that in just a moment.
2.5. ENABLE NODE TO RUN FROM ANY DIRECTORY 13
In the upper box of Environment Variables window (where it says user variables
for YourUserName) click on Path and click Edit... button.
In next window, click New and type C:\Program Files\nodejs on a new line:
2.7 Congratulations!
You have just installed Node on your computer.
16 CHAPTER 2. INSTALLATION
Chapter 3
Running Applications
17
18 CHAPTER 3. RUNNING APPLICATIONS
Then, use mkdir app to create new directory C:\app and enter it with cd app.
You don’t have to import or require any modules to use process object.
It is available in the module scope of your application by default.
3.2. RUNNING A FILE VIA NODE 19
Let’s run our index.js file via node to see what happens. Make sure you are in
C:\app and type the following command in cmd:
node index.js must be executed from same folder where you have index.js file.
The only reason we can run node (actually node.exe) from this folder is because
we added its installation path to our environment variables in an earlier step. So
if you get an error, make sure to complete that step first!
This runs the single line of code console.log(process) from our index.js script.
See the output on the next page.
20 CHAPTER 3. RUNNING APPLICATIONS
This Node process object contains all kinds of useful configuration properties.
For example process.versions.v8 tells you V8 engine version it’s running on.
3.4. ADDING PACKAGES TO INDEX.JS 21
Update index.js file with above code and run node index.js command:
Copy code above into index.js and let’s run it via node index.js command:
Note that we used 127.0.0.1 (It is the same as localhost) with port 3000.
24 CHAPTER 3. RUNNING APPLICATIONS
3.7 Congratulations!
The request shows up as / because we’re accessing just the IP address. It maps
to the root directory of our application.
Now enter http://127.0.0.1:3000/index.html and watch cmd window:
The file index.html doesn’t even exist yet. All we do is intercept incoming requests
and print them out.
Because we are not sending anything at all back to the browser, you will be stuck
on this page ”waiting for 127.0.0.1...”:
3.7. CONGRATULATIONS! 25
Now you know what happens when you try to go to a website and that little note
in the lower left corner appears!
The bar is spinning and it’s only a matter of time until you get the following:
26 CHAPTER 3. RUNNING APPLICATIONS
Request timed out. But you can terminate the server yourself with Ctrl + C:
Every time you want to terminate the server manually use this combo. This can
become useful if your server is stuck in an infinite loop or processing a long script.
Conclusion
From here on you will build out the rest of your server architecture. The remainder
of this book will walk you through how to install MySQL and write code for
implementing your own API. You can then use this API to build your application.
Chapter 4
So far we learned how to serve requested files. But if you want to build real web
applications, you might want to integrate support for API endpoints.
An endpoint is a URL that follows a special pattern. We can intercept this pattern
and upon its presence we will execute an API command, instead of serving a file.
This API command is likely to establish a database connection and either modify
or fetch some type of data. Our server can return a JSON object containing
requested data.
We will take a look at how to create some API end points for our existing Node
server. And then we will install MySQL and execute some queries. Using this
pattern you can build out the rest of your API.
Here is an example of an API endpoint that gets user info:
When this type of URL is requested, we will cancel serving the file, run some
server-side commands and return a result.
29
30 CHAPTER 4. BUILDING THE API
This gives us ability to include mysql as a module in our server-side .js scripts:
5.1 MySQL
You can run a MySQL server directly from your computer on localhost – the
home address of your computer as part of your local development environment.
Or you can run it on a remote server (a paid web host, for example.)
33
34 CHAPTER 5. SETTING UP MYSQL SERVER
This will have your Linux system updated with fresh URLs to latest packages. So
when you install mysql in the next step most recent update will be used.
Installation will begin and files will start downloading to your hard drive.
At this point you will see a stream of commands flowing on your screen.
Type Y / yes and press Enter if you are ever asked any questions.
Assuming mysql installation was successful, you can now use the ufw utility
program (Which stands for Uncomplicated Firewall.)
Note, our command starts with sudo which simply runs any program (ufw in this
case) using security privileges of another user.
sudo originally meant superuser do because on older Linux versions it was de-
signed to run only as superuser (usually root). Nowadays, you can use it to
execute commands using any username/password pair on the system. The mean-
ing of sudo acronym was gracefully re-formed substitute user do for said reason.
Uncomplicated Firewall
You can use ufw allow and ufw disallow commands to allow incoming and
outgoing traffic from a program. Without any additional options it is assumed you
are giving full access rights to this program. The ufw command has many other
options, and you can even allow connections on a specific port. Look it up online
if you need the complete documentation.
If you run just the mysql command now, you will enter mysql prompt.
But... it’s important to use mysql -u root -p instead.
This logs you in as root user, which gives you special privileges.
You will be prompted for your MySQL root user password. Enter it!
Then you should be greeted with mysql >:
Welcome to mysql prompt. This means your MySQL server is running and it’s
ready to receive MySQL commands. Every standard MySQL command you can
execute via code will work in this prompt as well.
5.1. MYSQL 37
You can also check current users by running Select User FROM mysql.user;
Note that mysql command keywords and table names are case insensitive. You
could have typed either Select User or SELECT user to the same effect!
5.1. MYSQL 39
If your my.cnf config looks like above, you need to find the actual mysql config-
uration file which should reside in one of the folders specified with !includedir.
Snoop around these folders to find the file with a similar .cnf name. In my case
it was mysqld.cnf, so I entered the following command to edit it:
nano /etc/mysql/mysql.conf.d/mysqld.cnf
5.1. MYSQL 41
Note below comments the file starts with [mysqld safe]. This is the recom-
mended way to start MySQL server on Unix. On Windows you will probably have
just [mysqld] in your config file, which may be called either my.ini or my.cfg.
[mysqld safe] tells MySQL server to restart in case of an error, among some other
helpful features. If you see this command you’re in the right MySQL config file.
If you are in the right MySQL config file, your cursor will jump to this line:
Final Words
Whenever you start a new project, if a hosted database is the only option, you will
probably want to open your MySQL database for remote access. This way you
can access it from your localhost environment without having to install MySQL
server on your machine.
However, this is usually considered bad security practice. At one point, you will
want to limit your MySQL database access to localhost only. This means only
your Node server can connect to the database directly.
This still doesn’t prevent database injection attacks.
Injection attacks use your API endpoints to pass actual MySQL query code into
one of the values sent together with the POST or GET requests.
By clever use of quote characters the query can be re-constructed to execute a
different MySQL command which can be virtually anything.
Keep this in mind when writing your endpoint code and generally thinking about
how to secure your database!
Writing MySQL Code
Now that we have our mysql server running and waiting for incoming user connec-
tions, we need to write some code on our Node back-end (index.js) as a starting
point for our MySQL-based API.
In the next chapter of this book we will add new mysql code by starting a connec-
tion to the server and executing a query. From that point on you can extend the
API by implementing the entire CRUD pattern.
CRUD
We already started api.js file earlier in this book, which – at this point – can only
interpret certain URL patterns as API endpoints and cancel serving the file.
But we are still not making any MySQL connections to the server. Nor are we
executing MySQL queries to actually Create, Read, Update or Delete rows –
collectively known as the CRUD API.
Once you implement the CRUD on your server, you will be ready to build out the
rest of your application. Usually the CRUD gives you ability to code pretty much
any feature on the front-end.
44 CHAPTER 5. SETTING UP MYSQL SERVER
Because our MySQL server is open for remote connection, it’s possible to log in
to it from Sequel Pro using felix account created earlier. If you set up MySQL
server on localhost use that as the Host. Otherwise use your web host’s database
IP address (which very often is the same IP address for your web hosting server.
It makes senes, because technically MySQL is installed on ”localhost” there too.)
5.2. TABLE SPECIMEN 45
Once logged into your favorite MySQL editor, create the user table that looks
similar to the following design:
Perhaps your table can be completely different. But for users at least have a
username and email address columns!
46 CHAPTER 5. SETTING UP MYSQL SERVER
Our barebones server requires only http, path, fs and mysql modules.
Note that the mysql object from MySQL package will return result in a separate
process in a callback function. So it’s a bit different from how you would expect
MySQL to work on a PHP server.
If we can find a way to handle the result and write back to the requesting client from
the callback, we can make API calls just as you would expect from Apache / PHP
setup. Think of it as an extra step. This makes Node MySQL API architecture a
bit more challenging, but also more flexible.
Chapter 6
Now that we have our database running either on localhost or at some remote
location, we’re ready to integrate our MySQL code into our server, so that we can
convert our API endpoint calls to MySQL queries.
Go to our app.js file and add lines highlighted in green to the very top of the file
(so that now we will have database and API classes together in the same file).
If you think class database should be Database, go ahead and change it to your
heart’s desires! The only reason it’s in lowercase is because we’re only using static
methods here, and in my opinion database.create looks more elegant.
47
48 CHAPTER 6. ADDING MYSQL TO API.JS
Make sure to replace XX.XX.XX.XXX with your actual web server IP, or if you’re
running Node server locally localhost (or 127.0.0.1).
Replace other XXXXX entries with your actual database username (felix), pass-
word (PassWord55723!) and database name – all of which were set up in the
previous section – or just use your own values.
The static function create() can now be used to create a database connection.
You can call database.create() once from the very top of index.js after require
6.1. ASYNCHRONOUS BACK-END PROBLEM 49
statements. Your server will connect to the MySQL database and you will be ready
to start executing MySQL queries.
Inside static function exec all we do is call connection.query method on our
database connection object.
If you are coming to Node from Apache PHP server, it is inevitable that you will
experience a paradigm shift, when trying to write your own mysql queries.
In PHP, in order to execute a mysql query, all you had to do was write a script
such as get user.php on the back-end.
Then you would use fetch API or a jQuery.ajax to call that file. The result would
be generated as part of the page content and returned inside the callback. This
way you could safely update the front end UI. We used to call this asynchronous
HTTP requests, or ”ajax” calls. It works naturally for updating the front end!
A Node callback doesn’t run in the same process with the function serving the file
to browser. So the file will be served before the mysql query returns! And this is
the fundamental problem we need to solve in order to build a decent API server.
Executing a MySQL query works exactly the same on Node. The result is returned
via a callback function in a separate process. And that’s part of the problem,
because we’re not on front-end anymore.
A callback will often depend on completion of another MySQL query. So we will
also need a way to execute a chain of multiple queries. And this can introduce a
whole new set of problems.
Solution. If we can somehow forge the process of serving the file with the result
we get from mysql query, we’re taking first step toward solving this problem.
One way of solving this problem is to use promises.
50 CHAPTER 6. ADDING MYSQL TO API.JS
Associative Tables
Let’s say you want to store followers of all existing users. You can’t store users
and followers in the same table because they are two completely different types
of data sets.
However, you can store followers in a separate table and ”associate” it with users
by adding userID column to it.
This way when you want to access an entry in followers table you can use the
userID column to look up which user it belongs to.
Nesting Queries
For the reason stated above, you will often need to write chains of nested queries.
To get followers from a user account, first you will retrieve a user from users
table. Then you will retrieve followers associated with that user’s primary key ID.
Because followers table has a link to the user via the user id column, you should
be able to gather a list of followers separately for that individual user.
Don’t forget the semicolon at the end of each mysql command or it will not run.
I’m running set global max connections = 300; to double connection limit:
52 CHAPTER 6. ADDING MYSQL TO API.JS
And if everything went well, running show variables like command should yield the
following result:
6.4.1 Promises
Promises add one extra layer to the standard callback pattern. When the Promise
returns, it returns a Promise object, instead of the callback function. This Promise
object is not guaranteed to carry a value yet, until it is resolved at a later time,
which is exactly why it’s called a promise. You can use the built-in .then method
on the Promise object to retrieve the results from the MySQL query.
The Promise’s .then method allows us to wait for the result and resolve it soon
as it becomes available even if it happens at a later time.
Using .then method allows you to avoid the nested callback pattern (or at least
reduce its occurence) where you keep nesting a callback within a callback, because
one API call depends on the data returned from the previous one.
Before we dive into source code, let’s look at how it all fits together, starting from
server listener and finally returning a value from MySQL query.
6.4. EXECUTING A MYSQL QUERY 55
Logging in should be treated as a special API action. It’s the only endpoint that
performs the initial authentication step.
6.6. HELPER FUNCTIONS 57
This is where you will take user’s password, encrypt it with an algorithm such as
SHA3, and compare it with the SHA3 password already stored in the database
under password sha3 in SHA3-encrypted format.
The primary purpose of logging in is to obtain an AuthToken. This becomes your
key to perform other authenticated endpoint actions – follow, tweet, retweet,
like, comment, update user settings, etc.
identify(target, action)
target argument is database table name (such as user, tweet, etc.) The action
argument is the ”what” you want to do to target (get, update, delete, etc.)
Figure 6.5: Identify an API endpoint request from API.parts. The API.parts
array is available globally. It represents the API endpoint call broken down into 3
parts. If there is a match, the return value is true.
respond(response, content)
The response argument is the response object from the server and content is a
string representing an object in JSON format (to send back to the browser) which
58 CHAPTER 6. ADDING MYSQL TO API.JS
json(chunks)
Figure 6.6: Form a JSON object from the streamed POST data chunks.
I intentionally keep my function names short and use common names. This way
when putting it all together the code turns out to be so much cleaner, readable
and easy to maintain down the road.
6.7. SENDING POST DATA TO API ENDPOINT 59
Going from here we can finish building out the entire round-trip pattern.
(See next page.)
6.8. STREAMING POST DATA 61
Knowing everything we do now, let’s upgrade our API class by adding support for
one endpoint to enable User Registration. This endpoint triggers the function we
wrote earlier: action user register
62 CHAPTER 6. ADDING MYSQL TO API.JS
Note that first we wait for POST data stream to finish. Only then we call identify
function to figure out the target and action details for the incoming request.
This request is created by URL that was typed into the address bar (or called
programmatically using the fetch API on the front-end.)
This is our core API end-point logic. Once the code is implemented, all we have
to do is continue adding new end-points to this pattern.
The next few pages will go over source code for some of the most common API
end-points you’ll have to build if you wish to create a user login based application
(which is pretty much all of them.)
So far we’ve only covered register user endpoint. It would take too much book
space on printing them all here. The rest of end-points can be found in api.js file
in the GitHub repository for this book:
https://github.com/javascriptteacher/node/
Under: /module/api/api.js
In this file you will find an object called Action with static functions attached to
it as follows:
back to the back-end to validate that the API action has returned (and whether
it failed or succeeded, which will be indicated by success property.)
You can’t make authenticated connections without understanding the concept of
sessions. Usually a session is stored in a separate database table with a unique
ID, Authentication Token ID, and a link back to the user ID from which the session
was initiated.
So let’s open a database editor (such as Sequel Pro on Mac) and add a new table
called session to existing database we created earlier in the book.
Luckily for us Node already has a module available to cover https and it’s easy
to switch! Just change ”http” to ”https”:
It’s up to you if you want to change variable name too but we’ll leave it intact so
we don’t break the rest of our code we’ve written so far.
66 CHAPTER 6. ADDING MYSQL TO API.JS
Let’s login to your web host as root user using ssh command. Just replace
XX.XXX.XX.XXX with the static IP address where you are hosting your website.
We should now be logged into the web host. (See server log on next page.)
6.12. LET’S ENCRYPT 67
You will be greeted by a screen similar to this. (I’m running Ubuntu 18.)
To install certbot we need to update the packages first. This is because certbot
developers continue applying improvements and your Ubuntu server may not have
the latest version on initial install.
Run sudo add-apt-repository ppa:certbot/certbot command to add certbot
repository to your Ubuntu server:
68 CHAPTER 6. ADDING MYSQL TO API.JS
Just press Enter and latest packages will be added to mirror files which is a list
of links pointing to the latest version of the packages.
Now run sudo apt-get update to actually download the updated packages:
This step is important - it will update your certbot packages to latest version.
If you find yourself on CentOS or Debian you can do the same thing as follows:
On CentOS run sudo yum update && sudo yum upgrade
On Debian run sudo apt update && sudo apt upgrade
Here the && symbols will cause your packages to be updated followed by being
upgraded without having to execute each command separately.
6.12. LET’S ENCRYPT 69
We can now use git command. Keep in mind that in this example we are in
bash.exe on Windows 10. If sudo or apt-get are not working, there is a work-
around.
First, if you are hosting your server remotely, use ssh in bash.exe to log into your
server, and all linux commands will become available over there.
Second, if you are developing on localhost and don’t need to log into your re-
mote host, you must install Ubuntu for Windows in addition to bash.exe (This is
explained in first chapter of this book.)
Third, if you are working directly on Linux, this doesn’t apply and apt-get should
work out of the box. If not, it can be installed manually.
Figure 6.7: Again, you might want to precede this command with sudo as shown
in the following example.
6.12. LET’S ENCRYPT 71
Figure 6.8: Again, you might want to precede this command with sudo as shown.
After this you will see letsencrypt-auto command generating the needed certifi-
cate files with certbot and creating http challenges automatically!
At this stage you might be asked several questions. I’m not going to include them
here to save book space. Just enter your email address when asked and few other
things. Choose (A)gree or (Y)es option every time asked.
On the next page, let’s take a look at what actually happened once the certificate
is generated:
6.12. LET’S ENCRYPT 73
Letsencrypt created and verified http challenges (this is needed in order to verify
that the domain name belongs to you, but in this instance this is done for us
automatically.)
Next... it also generated two pem keys for our example.com domain name.
Congratulations! At this point your domain name is https-enabled.
But there is one more thing. Let’s check where the files live and get familiar with
the directory where the keys were actually generated:
Let’s output contents of live directory. This is where letsencrypt will store all
certificate keys for all domain names on the server under respective folder name.
Inside example.com directory you will find several pem files generated by letsen-
crypt. We only need cert.pem and privkey.pem
We’re ready to start using the certificate. All we need to do is add some new code
to the existing index.js file.
You can skip the next section and jump over to Adding PEM files to run
HTTPS server section.
6.12. LET’S ENCRYPT 75
If you completed steps to install the SSL certificate in previous section you don’t
need to do this next step. But in some cases ACME challenges allow you to verify
that you are the owner of domain name.
I repeat, skip it! I just provided it here for reference.
Run certbot certonly –manual or certbot certonly –manual (note this is
actually double dash as shown below, not one dash.)
If you’re hosting multiple domains, you can use the same certificate, so just specify
as many domain names as you need separated by space or comma. In this case
we’re simply adding example site awesomesite.com
Enter your domain name (without www.) and press Enter.
To verify we own the domain name, we need to manually create the file named
afBX9EXvQqUqzFooe02-22EfJ5TzcniFw7CvqlaMXCA – just the part be-
fore the dot (.) highlighted in yellow in screenshot above.
Place this file into your .well-known/acme-challenge directory on your server.
(The root folder of your site.) You might have to create these folders first.
Now edit the contents of that file by pasting the whole string generated by certbot
into it. In our case it is the long text afBX9EXvQqUqzFooe02-22EfJ5TzcniFw
7CvqlaMXCA.rX9ThTxJ4y47aLEr7xgEWcOm4v7Jr5kJeT4PLA98-0
Keep in mind that this filename will be generated every time you run certbot. So
if you’ve already ran this command before it should be changed again.
Press Enter to Continue.
At this point certbot will verify existence of the file. Again, if you used the first
method in this section without acme challenge, you should be good to go.
6.12. LET’S ENCRYPT 77
Update the index.js file with code above. Log into your web host. Navigate to
the root directory of your application and run node index. Believe it or not, if all
goes well, at this point your server will be accessible via https protocol, and the
”Not Secure” message in Chrome (and other browsers) will disappear.
6.12. LET’S ENCRYPT 79
POST data is not available until request produces ”end” event. This is where we
put the chunks together into actual JSON object using the json helper function.
To add support for more endpoints just follow the same pattern. Place them inside
request.on(’end’)’s callback which ensures POST data finished streaming:
6.12. LET’S ENCRYPT 81
The request and response objects come all the way from initial call to
http.createServer(function(request, response)... in index.js. In other words,
in Node they are created automatically by createServer function.
82 CHAPTER 6. ADDING MYSQL TO API.JS
Press on the API endpoint test buttons and watch console. Remember that each
one of our endpoints returns a JSON object. This object has a property ”success”,
6.13. COMPLETE SOURCE CODE 83
which can be either true or false. The ”message” property will contain detailed
information about what happened.
For example:
{success: false, message: ”user with this ID does not exist.”}
{success: true, message: ”user (felix) was successfully registered!”}
Based on the success value you can update the front-end.
These endpoints are ready for integration into your own front-end UI/UX. You can
call them via onclick attribute or elsewhere from your JavaScript code.
Multer is a good module that helps with file uploads from an HTML form. To get
it simply run npm install multer command in Terminal or cmd.exe/bash.exe.
84 CHAPTER 6. ADDING MYSQL TO API.JS
that when you launch your Node server, it will be copied into a JavaScript object.
When client requests a certain resource we can simply serve it directly from that
object. It will contain a copy of the data your MySQL database would contain.
But your application will become significantly more efficient.
You will still write this object to the hard drive, so it can permanently store the
most recent data, but not as frequently as you would with a 100% MySQL setup.
Some databases such as MongoDB also implement similar RAM caching features.
But they still may not be optimized for the primary purpose of your application
which only you know. Thus missing the chance of taking advantage of the full
potential of your server’s horsepower.
And just like with anything else, you can either ”install a package,” or install and
configure existing software, or you can learn to write your own code. Without the
latter, you may never be able to understand or develop the skill of building an
extremely efficient system for serving millions of users.
Unfortunately, this architecture will not be covered in 1st edition of this book due
to time constraints I’ve had within which I had to finish this volume. However, I
plan on second edition where I will go into greater detail on the subject. For now,
the least I could do is to give you a pointer in the right direction.
86 CHAPTER 6. ADDING MYSQL TO API.JS
Let’s kill database connection every time server exits for any reason.
your client, teammates, investors, friends or others who can test the new version
of the application before the public release, and 2] you can make sure deployment
process doesn’t break the main production server with new unexpected bugs.
The stage server can be used to test integrity of the newly deployed code, without
risking the chance of deploying erroneous code directly to master, losing customers
and having a panic attack.
Now you are thinking like a real production engineer!
Both master and stage are nothing more than two versions of your application
running separately in two different locations. So I won’t talk about how to set up
a stage server – the process is exactly the same. The difference is in where you
push your code to.
6.17 Conclusion
At this point you should be ready to host your own secure SSL applications from
https://www.appname.com if you indeed followed all instructions described in
this book up to this point.
In the next edition I will cover scaling your application and making it accessible by
millions of simultaneous users. There is currently no set date as to when it will
come out, but follow my work at @js tut on Twitter for a future announcement.
I hope that this Node API book was a faithful guide on your journey to becoming
a software developer. Thanks for reading!
88 CHAPTER 6. ADDING MYSQL TO API.JS
Look for a copy of JavaScript Grammar on Amazon. (cover art may vary.)
Index
89
90 INDEX
ufw, 35 Windows, 9