Node.js Express Framework
Introduction to Express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features to help you create various web applications and rich HTTP utilities.
Using Express, you can quickly set up a fully functional website.
Core features of the Express framework:
- Can set up middleware to respond to HTTP requests.
- Defines a routing table to perform different HTTP request actions.
- 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 will install the Express framework in the nodemodules directory of the current directory, and the nodemodules directory will automatically create an express directory. The following important modules need to be installed along with the express framework:
- body-parser - Node.js middleware for handling JSON, Raw, Text, and URL-encoded data.
- cookie-parser - A tool for parsing cookies. You can retrieve cookies sent by the request through req.cookies and convert them into objects.
- multer - Node.js middleware for handling
enctype="multipart/form-data"
(MIME encoding of forms) form data.$ cnpm install body-parser --save $ cnpm install cookie-parser --save $ cnpm install multer --save
After installation, we can check the version of Express used:
$ cnpm list express
/data/www/node
└── [email protected] -> /Users/tianqixin/www/node/node_modules/.4.15.2@express
First Express Framework Example
Next, we will use the Express framework to output "Hello World".
In the following example, we introduce the express module and respond with the string "Hello World" after the client makes 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 instance, access address is http://%s:%s", host, port)
})
Execute the above code:
$ node express_demo.js
Application instance, access address is http://0.0.0.0:8081
Visit http://127.0.0.1:8081 in your browser, and the result will be as shown below:
Request and Response
Express applications use callback function parameters: request and response objects to handle request and response data.
app.get('/', function (req, res) {
// --
})
Detailed introduction of Request and Response 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: Access the express instance when the callback is an external file
- req.baseUrl: Get the URL path where the route is mounted
- req.body / req.cookies: Get the "request body" / Cookies
- req.fresh / req.stale: Determine if 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's parameters
- req.path: Get the request path
- req.protocol: Get the protocol type
- req.query: Get the query parameters of the URL
Response Object - The response object represents the HTTP response that an Express app sends when it gets an HTTP request.
- req.route: Get the current matched route
- req.subdomains: Get subdomains
- req.accepts(): Check the accepted document types for the request
- req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: Return the first acceptable charset encoding
- 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 the HTTP response that is sent to the client when a request is received. Common properties include:
- res.app: Same as req.app
- res.append(): Append specified HTTP header
- res.set() will reset the header set after res.append()
- res.cookie(name, value [, option]): Set a cookie
- option: domain / expires / httpOnly / maxAge / path / secure / signed
- res.clearCookie(): Clear a cookie
- res.download(): Transfer the 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(): Set only the Location HTTP header of the response without setting status code or closing the response
- res.redirect(): Set the Location HTTP header of the response and set 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, next(err) will be called automatically. The callback will be passed the possible error and the rendered page, so it will not be automatically output.
- res.send(): Send an HTTP response
- res.sendFile(path [, options] [, fn]): Send the file at the specified path
- Automatically sets the Content-Type based on the file extension
- res.set(): Set HTTP headers, passing an object allows setting multiple headers at once
- res.status(): Set the HTTP status code
- res.type(): Set the MIME type of the Content-Type
Routing
We have learned the basic application of HTTP requests, and routing determines which script responds to the client's request.
In an HTTP request, we can extract the URL and GET/POST parameters through routing.
Next, we will expand the Hello World example by adding 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();
// Home page outputs "Hello World"
app.get('/', function (req, res) {
console.log("Home page GET request");
res.send('Hello GET');
})
// POST request
app.post('/', function (req, res) {
console.log("Home page POST request");
res.send('Hello POST');
})
// /del_user page response
app.get('/del_user', function (req, res) {
console.log("/del_user DELETE request response");
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 like abcd, abxcd, ab123cd, etc.
app.get('/ab*cd', function(req, res) {
console.log("/ab*cd GET request");
res.send('Regex match');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port;
console.log("Application instance, access address is http://%s:%s", host, port);
});
Execute the above code:
$ node express_demo2.js
Application instance, access address is http://0.0.0.0:8081
Next, you can try accessing different addresses such as http://127.0.0.1:8081 to see the effects.
In the browser, access http://127.0.0.1:8081/list_user, the result is as shown below:
In the browser, access http://127.0.0.1:8081/abcd, the result is as shown below:
In the browser, access http://127.0.0.1:8081/abcdefg, the result is as shown below:
Static Files
Express provides built-in middleware express.static for serving static files such as images, CSS, JavaScript, etc.
You can use express.static middleware to set the path for static files. For example, if you place images, CSS, JavaScript files in the public directory, you can write it like this:
app.use('/public', express.static('public'));
We can place 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 to add the functionality of handling 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 instance, access address is http://%s:%s", host, port);
})
Execute the above code:
$ node express_demo3.js
Application instance, access address is http://0.0.0.0:8081
In the browser, access http://127.0.0.1:8081/public/images/logo.png (this example uses the logo from tutorialpro.org), the result is as shown below:
GET Method
The following example demonstrates submitting two parameters via the GET method in a form. We can use the process_get router in the server.js file to handle the input:
index.html File Code:
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
server.js File Code:
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 instance, access address is http://%s:%s", host, port)
})
Executing the above code:
node server.js
Application instance, access address is http://0.0.0.0:8081
Visit http://127.0.0.1:8081/index.html in the browser, as shown in the figure:
Now you can enter data into the form and submit it, as demonstrated below:
POST Method
The following example demonstrates submitting two parameters via POST method in a form. We can use the process_post router in the server.js file to 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"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
server.js File Code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded encoding parser
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 instance, access address is http://%s:%s", host, port)
})
Executing the above code:
$ node server.js
Application instance, access address is http://0.0.0.0:8081
Visit http://127.0.0.1:8081/index.html in the browser, as shown in the figure:
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 enctype attribute set to multipart/form-data.
index.html File Code:
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
<h3>File 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 File" />
</form>
</body>
</html>
## server.js File Code:
```javascript
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 instance, access address is http://%s:%s", host, port)
})
Executing the above code:
$ node server.js
Application instance, access address is http://0.0.0.0:8081
Visit 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 cookies 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)
Executing 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/
Express 4.x API Chinese Version: Express 4.x API Chinese Express 4.x API: http://expressjs.com/en/4x/api.html