Node.js Express Framework
Introduction to Express
Express is a concise and flexible Node.js web application framework that provides a series of powerful features to help you create various web applications, along with rich HTTP utilities.
Using Express, you can quickly build a fully functional website.
Core Features of the Express Framework:
-
You can set up middleware to respond to HTTP requests.
-
It defines a routing table for handling different HTTP request actions.
-
You can dynamically render HTML pages by passing parameters to templates.
Installing Express
Install Express and save it to the dependency list:
$ cnpm install express --save
The above command installs the Express framework in the node_modules directory of the current directory; node_modules the express directory is automatically created under that directory. The following important modules need to be installed together with the Express framework:
-
body-parser - Node.js middleware for handling JSON, Raw, Text, and URL-encoded data.
-
cookie-parser - This is a tool for parsing cookies. Through req.cookies you can retrieve the cookies passed in and convert them into objects.
-
multer - Node.js middleware for handling form data with enctype="multipart/form-data" (setting the form's MIME encoding).
$ cnpm install body-parser --save
$ cnpm install cookie-parser --save
$ cnpm install multer --save
After installation, we can check the version of Express in use:
$ cnpm list express
/data/www/node
└── express@4.15.2 -> /Users/tianqixin/www/node/node_modules/.4.15.2@express
First Express Framework Example
Next, we use the Express framework to output "Hello World".
In the following example, we import the express module and respond with the "Hello World" string after the client initiates a request.
Create an express_demo.js file with the following code:
express_demo.js file code:
//
express_demo.js File
var
express
=
require
(
'
express
'
)
;
var
app
=
express
(
)
;
app
.
get
(
'
/
'
,
function
(
req
,
res
)
{
res
.
send
(
'
Hello World
'
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
$ node express_demo.js
应用实例,访问地址为 http://0.0.0.0:8081
Visit http://127.0.0.1:8081 in a browser, and the result is shown below:

Requests and Responses
Express applications use the parameters of the callback function: request and response objects to handle request and response data.
app.get('/', function (req, res) {
// --
})
request and response Detailed introduction to the objects:
Request Object - The request object represents the HTTP request and contains properties such as the query string, parameters, content, and HTTP headers. Common properties include:
- req.app: When the callback is in an external file, use req.app to access the Express instance
- req.baseUrl: Get the URL path on which the router is currently mounted
- req.body / req.cookies: Get the request body / Cookies
- req.fresh / req.stale: Determine whether the request is still "fresh"
- req.hostname / req.ip: Get the hostname and IP address
- req.originalUrl: Get the original request URL
- req.params: Get the route parameters
- req.path: Get the request path
- req.protocol: Get the protocol type
- req.query: Get the URL query parameter string
- req.route: Get the currently matched route
- req.subdomains: Get subdomains
- req.accepts(): Check the acceptable document types of the request
- req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: Return the first acceptable character encoding for the specified character set
- req.get(): Get the specified HTTP request header
- req.is(): Determine the MIME type of the request header Content-Type
Response Object - The response object represents an HTTP response, that is, the HTTP response data sent to the client when a request is received. Common properties include:
- res.app: Same as req.app
- res.append(): Append the specified HTTP header
- res.set() will reset the previously set headers after res.append()
- res.cookie(name,value [,option]): Set a Cookie
- opition: domain / expires / httpOnly / maxAge / path / secure / signed
- res.clearCookie(): Clear a Cookie
- res.download(): Transfer a file at the specified path
- res.get(): Return the specified HTTP header
- res.json(): Send a JSON response
- res.jsonp(): Send a JSONP response
- res.location(): Only sets the response's Location HTTP header; it does not set the status code or close the response
- res.redirect(): Sets the response's Location HTTP header and sets the status code to 302
- res.render(view,[locals],callback): Render a view and pass the rendered string to the callback. If an error occurs during rendering, next(err) will be called automatically. The callback will be passed a possible error and the rendered page, so nothing will be output automatically.
- res.send(): Send an HTTP response
- res.sendFile(path [,options] [,fn]): Transfer a file at the specified path - the Content-Type is automatically set based on the file extension
- res.set(): Set HTTP headers; passing an object can set multiple headers at once
- res.status(): Set the HTTP status code
- res.type(): Set the MIME type of Content-Type
Routing
We have already learned the basics of HTTP requests, and routing determines who (the specified script) responds to the client request.
In HTTP requests, we can use routing to extract the request URL and GET/POST parameters.
Next we will extend Hello World, adding some functionality to handle more types of HTTP requests.
Create the express_demo2.js file with the following code:
express_demo2.js file code:
var
express
=
require
(
'
express
'
)
;
var
app
=
express
(
)
;
//
Homepage outputs "Hello World"
app
.
get
(
'
/
'
,
function
(
req
,
res
)
{
console
.
log
(
"
Homepage GET request
"
)
;
res
.
send
(
'
Hello GET
'
)
;
}
)
//
POST request
app
.
post
(
'
/
'
,
function
(
req
,
res
)
{
console
.
log
(
"
Homepage POST request
"
)
;
res
.
send
(
'
Hello POST
'
)
;
}
)
//
/del_user page response
app
.
get
(
'
/del_user
'
,
function
(
req
,
res
)
{
console
.
log
(
"
/del_user responds to DELETE requests
"
)
;
res
.
send
(
'
Delete page
'
)
;
}
)
//
/list_user page GET request
app
.
get
(
'
/list_user
'
,
function
(
req
,
res
)
{
console
.
log
(
"
/list_user GET request
"
)
;
res
.
send
(
'
User list page
'
)
;
}
)
//
Respond to GET requests for pages abcd, abxcd, ab123cd, etc.
app
.
get
(
'
/ab*cd
'
,
function
(
req
,
res
)
{
console
.
log
(
"
/ab*cd GET request
"
)
;
res
.
send
(
'
Regex Matching
'
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
$ node express_demo2.js
应用实例,访问地址为 http://0.0.0.0:8081
Next you can try accessing different addresses at http://127.0.0.1:8081 to see the result.
Access http://127.0.0.1:8081/list_user in your browser; the result is shown below:
Access http://127.0.0.1:8081/abcd in your browser; the result is shown below:
Access http://127.0.0.1:8081/abcdefg in your browser; the result is shown below:
Static files
Express provides a built-in middleware ** express.static ** to set up static files such as images, CSS, JavaScript, etc.
You can use the ** express.static ** middleware to set up a static file path. For example, if you place images, CSS, and JavaScript files in the public directory, you can write it like this:
app.use('/public', express.static('public'));
We can put some images in the public/images directory, as shown below:
node_modules
server.js
public/
public/images
public/images/logo.png
Let's modify the "Hello World" application again to add the ability to handle static files.
Create the express_demo3.js file with the following code:
express_demo3.js file code:
var
express
=
require
(
'
express
'
)
;
var
app
=
express
(
)
;
app
.
use
(
'
/public
'
,
express
.
static
(
'
public
'
)
)
;
app
.
get
(
'
/
'
,
function
(
req
,
res
)
{
res
.
send
(
'
Hello World
'
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
$ node express_demo3.js
应用实例,访问地址为 http://0.0.0.0:8081
Execute the above code:
Access http://127.0.0.1:8081/public/images/logo.png in your browser (this example uses the Runoob Tutorial logo); the result is shown below:
GET Method
The following example demonstrates submitting two parameters through a form using the GET method; we can use the router in the server.js file to process_get handle the input:
index.html file code:
<
html
<
body
<
form
action
=
"
/process_get
"
method
=
"
GET
"First Name:
<
input
type
=
"
text
"
name
=
"
first_name
"
<
brLast Name:
<
input
type
=
"
text
"
name
=
"
last_name
"
<
input
type
=
"
submit
"
value
=
"
Submit
"
form
body
html
var
express
=
require
(
'
express
'
);
var
app
=
express
(
)
;
app
.
use
(
'
/public
'
,
express
.
static
(
'
public
'
)
)
;
app
.
get
(
'
/index.html
'
,
function
(
req
,
res
)
{
res
.
sendFile
(
__dirname
"
/
"
"
index.html
"
)
;
}
)
app
.
get
(
'
/process_get
'
,
function
(
req
,
res
)
{
//
Output JSON format
var
response
=
{
"
first_name
"
:
req
.
query
.
first_name
,
"
last_name
"
:
req
.
query
.
last_name
}
;
console
.
log
(
response
)
;
res
.
end
(
JSON
.
stringify
(
response
)
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
node server.js
应用实例,访问地址为 http://0.0.0.0:8081
Access http://127.0.0.1:8081/index.html in your browser, as shown below:
Now you can enter data into the form and submit it, as demonstrated below:
POST Method
The following example demonstrates submitting two parameters through a form using the POST method; we can use the body-parser middleware in the server.js file to process_post handle the input:
index.html file code:
<
html
<
body
<
form
action
=
"
http://127.0.0.1:8081/process_post
"
method
=
"
POST
"First Name:
<
input
type
=
"
text
"
name
=
"
first_name
"
<
brLast Name:
<
input
type
=
"
text
"
name
=
"
last_name
"
<
input
type
=
"
submit
"
value
=
"
Submit
"
form
body
html
var
express
=
require
(
'
express
'
);
var
app
=
express
(
)
;
var
bodyParser
=
require
(
'
body-parser
'
)
;
//
Create application/x-www-form-urlencoded encoding parsing
var
urlencodedParser
=
bodyParser
.
urlencoded
(
{
extended
:
false
}
)
app
.
use
(
'
/public
'
,
express
.
static
(
'
public
'
)
)
;
app
.
get
(
'
/index.html
'
,
function
(
req
,
res
)
{
res
.
sendFile
(
__dirname
"
/
"
"
index.html
"
)
;
}
)
app
.
post
(
'
/process_post
'
,
urlencodedParser
,
function
(
req
,
res
)
{
//
Output JSON format
var
response
=
{
"
first_name
"
:
req
.
body
.
first_name
,
"
last_name
"
:
req
.
body
.
last_name
}
;
console
.
log
(
response
)
;
res
.
end
(
JSON
.
stringify
(
response
)
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
$ node server.js
应用实例,访问地址为 http://0.0.0.0:8081
Access http://127.0.0.1:8081/index.html in your browser, as shown below:
Now you can enter data into the form and submit it, as demonstrated below:
File upload
Below we create a form for uploading files, using the POST method, with the form's enctype attribute set to multipart/form-data.
index.html file code:
<
html
<
head
<
titleFile upload form
title
head
<
body
<
h3File upload:
h3
Select a file to upload:
<
br
/>
<
form
action
=
"
/file_upload
"
method
=
"
post
"
enctype
=
"
multipart/form-data
"
<
input
type
=
"
file
"
name
=
"
image
"
size
=
"
50
"
/>
<
br
/>
<
input
type
=
"
submit
"
value
=
"Upload files
"
/>
form
body
html
server.js file code:
var
express
=
require
(
'
express
'
)
;
var
app
=
express
(
)
;
var
fs
=
require
(
"
fs
"
)
;
var
bodyParser
=
require
(
'
body-parser
'
)
;
var
multer
=
require
(
'
multer
'
)
;
app
.
use
(
'
/public
'
,
express
.
static
(
'
public
'
)
)
;
app
.
use
(
bodyParser
.
urlencoded
(
{
extended
:
false
}
)
)
;
app
.
use
(
multer
(
{
dest
:
'
/tmp/
'
}
)
.
array
(
'
image
'
)
)
;
app
.
get
(
'
/index.html
'
,
function
(
req
,
res
)
{
res
.
sendFile
(
__dirname
"
/
"
"
index.html
"
)
;
}
)
app
.
post
(
'
/file_upload
'
,
function
(
req
,
res
)
{
console
.
log
(
req
.
files
[
0
]
)
;
//
Uploaded file information
var
des_file
=
__dirname
"
/
"
req
.
files
[
0
]
.
originalname
;
fs
.
readFile
(
req
.
files
[
0
]
.
path
,
function
(
err
,
data
)
{
fs
.
writeFile
(
des_file
,
data
,
function
(
err
)
{
if
(
err
)
{
console
.
log
(
err
)
;
}
else
{
response
=
{
message
:
'
File uploaded successfully
'
,
filename
:
req
.
files
[
0
]
.
originalname
}
;
}
console
.
log
(
response
)
;
res
.
end
(
JSON
.
stringify
(
response
)
)
;
}
)
;
}
)
;
}
)
var
server
=
app
.
listen
(
8081
,
function
(
)
{
var
host
=
server
.
address
(
)
.
address
var
port
=
server
.
address
(
)
.
port
console
.
log
(
"
Application example, access the address http://%s:%s
"
,
host
,
port
)
}
)
Execute the above code:
$ node server.js
应用实例,访问地址为 http://0.0.0.0:8081
Access http://127.0.0.1:8081/index.html in your browser, as shown below:
Now you can enter data into the form and submit it, as demonstrated below:
Cookie Management
We can use middleware to send cookie information to the Node.js server; the following code outputs the cookie information sent by the client:
express_cookie.js file code:
//
express_cookie.js file
var
express
=
require
(
'
express
'
)
var
cookieParser
=
require
(
'
cookie-parser
'
)
var
util
=
require
(
'
util
'
)
;
var
app
=
express
(
)
app
.
use
(
cookieParser
(
)
)
app
.
get
(
'
/
'
,
function
(
req
,
res
)
{
console
.
log
(
"
Cookies:
"
util
.
inspect
(
req
.
cookies
)
)
;
}
)
app
.
listen
(
8081
)
Execute the above code:
$ node express_cookie.js
Now you can access http://127.0.0.1:8081 and view the terminal output, as demonstrated below:
Related resources
- Express official website: http://expressjs.com/
- Express4.x API Chinese version: Express4.x API Chinese
- Express4.x API:http://expressjs.com/zh-cn/4x/api.html