Node.js
:
HTTP
module to abstract away complex
network-related
operations.
request
coming from the client and produces the response
. The function takes two arguments: 1)
an object representing the request
and 2) an object representing the response
.
index.js
file inside.
index.js
file:
node index.js
to execute your file. A message that
reads "_Server running at _http://127.0.0.1:3000" should be displayed, and the
server is now waiting for
connections.
http://localhost:3000
. localhost
and the IP address 127.0.0.1
point to the same thing: your local
computer. The browser should show the
message: "Hello World from Node". There you have it, your first
web server, built from scratch using
nothing but Node.js
.
HTTP
module provides a powerful way to build
web applications and services. However,
it requires a lot of code for everyday
tasks like sending an HTML page to the
browser.
sendFile
helper method in Express
.
connect
.
response.redirect()
, response.status()
, response.send()
, and request.ip
.
server.js
to host our server code.
npm init -y
to generate a package.json
.
express
npm module using: npm install express
.
server.js
add the following code:
node server.js
and visit http://localhost:5000
in the browser.
Ctrl + c
at the terminal window.
GET
request. The program should return the
string every time a request comes into
the root route ("/"). For now,
you don't need to code along, just
read through the steps.
cd
.
npm install
to download all
dependencies.
index.js
at the folder's root, next
to the package.json
file.
index.js
file using our favorite code
editor.
index.js
.
express
npm module in our code, so we need to
add it as a dependency to our project.
To do this:
package.json
file by typing npm install express
.
npm run server
to run our API. The message "Api running on port
8000"
should appear on the
terminal.
require()
to import
the express module
and make it available to our
application. require()
is similar to the import
keyword we have used before. The line const express =
require('express');
is equivalent to import express from
'express';
if we were using ES2015 syntax.
express()
is an instance of an Express application
that we can use to configure our server
and, eventually, start listening for and
responding to requests. Notice we use
the word server, not API. An Express
application is generic, which means we
can use it to serve static content
(HTML, CSS, audio, video, PDFs, and
more). We can also use an Express
application to serve dynamically
generated web pages, build real-time
communications servers, and more. We
will use it statically to accept
requests from clients and respond with
data in JSON format.
.get()
method to set up a route handler
function that will run on every GET
request. As a part of this handler
function, we specify the URL which will
trigger the request. In this case, the
URL is the site's root (represented
by a /
). There are also methods to handle the POST
, PUT
, and DELETE
HTTP verbs.
express
to a route handler function are 1) an
object representing the request
and 2) an object representing the response
. Express expands those objects with a
set of useful properties and methods.
Our example uses the .send()
method of the response object to specify
the data we will send to the client as
the response body. You can call the
first two arguments anything you want,
but it is prevalent to see them dubbed req
and res
.
.listen()
method to monitor a port on the computer
for any incoming connections and respond
to those we have configured. Our server
will only respond to GET
requests made to the /
route on port 8000
.
index.js
instead of typing it. Then run your API
through a browser to make sure it
works.
GET
requests at the /hobbits
endpoint.
hobbits
array. We could use .send(hobbits)
as we did for the string on the /
endpoint, but this time we'll learn
about two other useful methods we find
in the response object.
HTTP status code
that reflects the client's
operation outcome. In this case, the
client is trying to get a list of a
particular resource
, a hobbits
list. Sending back a 200 OK
status code communicates to the client
that the operation was successful.
.status()
method of the response object to send
any valid HTTP status code
.
.json()
method of the response object. We do
this to communicate to both the client
making the request and the next
developer working with this code that we
intend to send the data in JSON format
.
index.js
should now look like so:
http://localhost:8000/hobbits
in our browser, and we should get back
our JSON array.
GET
requests on different URLs, add the
following endpoints:
1.) We are using the same HTTP Method on both endpoints, but express looks at the URL and executes the corresponding request handler.2.) We can return a string with valid HTML!
/about
and /contact
routes. The appropriate route handler
will execute.
GET
endpoint to /hobbits
:
POST
operations.
PUT
requests to the same URL.
PUT
operations, we use HTTP Status Code 200
(OK).
DELETE
requests.
Postman
to test our POST
, PUT
, and DELETE
endpoints.
DELETE
endpoint.
route parameters
. Let's add support for route
parameters to our DELETE
endpoint.
:
) in front of it. Express adds it to
the .params
property part of the request object.
Let's see it in action:
DELETE
for a URL that begins with /hobbits/
followed by any value. So, DELETE
requests to /hobbits/123
and /hobbits/frodo
will both trigger this request handler.
The value passed after /hobbits/
will end up as the id
property on req.params
.
string
, even if the value passed is numeric.
When hitting /hobbits/123
in our example, the type of req.params.id
will be string
.
/hobbits/:id/friends/:friendId
, will add properties for id
and friendId
to req.params
.
key=value
, and pairs are separated by an &
. To mark the beginning of the query
string, we add ?
and the end of the URL, followed by the
set of key/value pairs.
https://www.google.com/search?q=lambda&tbo=1
. The query string portion is ?q=lambda&tbo=1
and the key/value pairs are q=lambda
and tbo=1
.
/hobbits
and pass the field they want to use to
sort the responses, and our API will
sort the data by that field in ascending
order.
GET /hobbits
endpoint:
localhost:8000/hobbits?sortby=name
, and the list should be sorted by name
. Visit localhost:8000/hobbits?sortby=id
, and the list should now be sorted by id
. If no sortby
parameter is provided, it should default
to sorting by id
.
req.query
object added by Express. There will be a
key and a value in the req.query
object for each key/value pair found in
the query string.
array
if more than one value is passed for the
same key and string
when only one value is passed. For
example, in the query string ?id=123
, req.query.id
will be a string, but for ?id=123&id=234
, it will be an array.
sortby
and sortBy
are two different parameters.
POST /hobbits
endpoint. We need to read the
hobbit's information to add it to
the hobbits
array. Let's do that next:
server.use(express.json());
after the express application
has been created.
Body
tab underneath the address
bar.
raw
radio button.
binary
radio button, select `JSON
(application/json).
Send
, and the API should return the list of
hobbits, including Sam!
PUT
endpoint and a way for the client to
specify the sort direction.
req.body
and use it to update the existing
hobbit.
id
from the req.params
object and reading the hobbit
information from req.body
. The rest of the code will change as
this is a simple example using an
in-memory array. Most production APIs
will use a database.
--trace-sync-io
command-line flag to print a warning and
a stack trace whenever your application
uses a synchronous API. Of course, you
wouldn’t want to use this in production,
but rather to ensure that your code is
ready for production. See the
node command-line options
documentation
for more information.
console.log()
or console.error()
to print log messages to the terminal is
common practice in development. But
these functions are
synchronous
when the destination is a terminal or a
file, so they are not suitable for
production, unless you pipe the output
to another program.
console.log()
, use a special debugging module like
debug. This module enables you to use the
DEBUG environment variable to control
what debug messages are sent to console.error()
, if any. To keep your app purely
asynchronous, you’d still want to pipe console.error()
to another program. But then, you’re not
really going to debug in production, are
you?
console.log()
, use a logging library like
Winston
or
Bunyan. For a detailed comparison of these
two libraries, see the StrongLoop blog
post
Comparing Winston and Bunyan
Node.js Logging.
uncaughtException
event, emitted when an exception bubbles
all the way back to the event loop.
Adding an event listener for uncaughtException
will change the default behavior of the
process that is encountering an
exception; the process will continue to
run despite the exception. This might
sound like a good way of preventing your
app from crashing, but continuing to run
the app after an uncaught exception is a
dangerous practice and is not
recommended, because the state of the
process becomes unreliable and
unpredictable.
uncaughtException
is officially recognized as
crude. So listening for uncaughtException
is just a bad idea. This is why we
recommend things like multiple processes
and supervisors: crashing and restarting
is often the most reliable way to
recover from an error.
then()
. Just add .catch(next)
to the end of promise chains. For
example:
wrap()
function is a wrapper that catches
rejected promises and calls next()
with the error as the first argument.
For details, see
Asynchronous Error Handling in
Express with Promises, Generators
and ES7.
process.env.NODE_ENV
. Be aware that checking the value of
any environment variable incurs a
performance penalty, and so should be
done sparingly.
export
or your .bash_profile
file. But in general you shouldn’t do
that on a production server; instead,
use your OS’s init system (systemd or
Upstart). The next section provides more
details about using your init system in
general, but setting NODE_ENV is so
important for performance (and easy to
do), that it’s highlighted here.
env
keyword in your job file. For
example:
Environment
directive in your unit file. For
example:
node server.js
or something similar. But doing this in
production is a recipe for disaster. If
the app crashes, it will be offline
until you restart it. To ensure your app
restarts if it crashes, use a process
manager. A process manager is a
“container” for applications that
facilitates deployment, provides high
availability, and enables you to manage
the application at runtime.