Node.js Express Framework


Express Introduction

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, and rich HTTP tools.

With Express, you can quickly build a fully functional website.

Express framework core features:

  • You can set up middleware to respond to HTTP requests.

  • A routing table is defined to execute different HTTP request actions.

  • You can dynamically render HTML pages by passing parameters to templates.


Install Express

Install Express and save it to the dependency list:

$ cnpm install express --save

The above command will install the Express framework in the current directory'snode_modulesdirectory,node_modulesAn express directory will be 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. You can get the incoming cookies via req.cookies and convert them into objects.

  • multer- Node.js middleware for handling form data with enctype="multipart/form-data" (sets the MIME encoding of the form).

$ cnpm install body-parser --save
$ cnpm install cookie-parser --save
$ cnpm install multer --save

After installation, we can check the version number used by express:

$ cnpm list express
/data/www/node
└── [email protected]  -> /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 introduce the express module and respond with the string "Hello World" after the client makes a request.

Create the 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 
应用实例,访问地址为 http://0.0.0.0:8081

Visit http://127.0.0.1:8081 in the browser, the result is shown in the figure below:


Request and Response

Express applications use the parameters of callback functions:requestandresponseobjects to handle request and response data.

app.get('/', function (req, res) {
   // --
})

requestandresponseDetailed introduction to the objects:

Request Object- The request object represents an HTTP request and contains properties such as the request query string, parameters, content, and HTTP headers. Common properties include:

  1. req.app: When the callback is an external file, use req.app to access the express instance
  2. req.baseUrl: Get the URL path where the route is currently mounted
  3. req.body / req.cookies: Get the "request body" / Cookies
  4. req.fresh / req.stale: Determine whether the request is still "fresh"
  5. req.hostname / req.ip: Get the hostname and IP address
  6. req.originalUrl: Get the original request URL
  7. req.params: Get the route's parameters
  8. req.path: Get the request path
  9. req.protocol: Get the protocol type
  10. req.query: Get the query parameter string of the URL
  11. req.route: Get the currently matched route
  12. req.subdomains: Get the subdomains
  13. req.accepts(): Check the acceptable document types for the request
  14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: Returns the first acceptable character encoding of the specified charsets
  15. req.get(): Get the specified HTTP request header
  16. req.is(): Determine the MIME type of the request header Content-Type

Response Object- The response object represents the HTTP response, i.e., the HTTP response data sent to the client upon receiving a request. Common properties include:

  1. res.app: Same as req.app
  2. res.append(): Append the specified HTTP header
  3. res.set() will reset the previously set headers after res.append()
  4. res.cookie(name, value [, option]): Set Cookie
  5. opition: domain / expires / httpOnly / maxAge / path / secure / signed
  6. res.clearCookie(): Clear Cookie
  7. res.download(): Transfer the file at the specified path
  8. res.get(): Return the specified HTTP header
  9. res.json(): Send a JSON response
  10. res.jsonp(): Send a JSONP response
  11. res.location(): Only set the Location HTTP header of the response, without setting the status code or closing the response.
  12. res.redirect(): Set the Location HTTP header of the response and set status code 302
  13. 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 automatically called. The callback will be passed any possible error and the rendered page, so there will be no automatic output.
  14. res.send(): Send an HTTP response
  15. res.sendFile(path [, options] [, fn]): Transfer the file at the specified path - Automatically sets Content-Type based on the file extension
  16. res.set(): Set HTTP headers; you can set multiple headers at once by passing an object
  17. res.status(): Set the HTTP status code
  18. res.type(): Set the MIME type of Content-Type

Routing

We have already learned the basic applications of HTTP requests, and routing determines who (the specified script) responds to client requests.

In HTTP requests, we can extract the requested URL and GET/POST parameters through routing.

Next, we extend Hello World by adding some features 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 responds to DELETE request"); 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('Regular expression matching'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Application example, access address is 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 like http://127.0.0.1:8081 to see the effect.

Access http://127.0.0.1:8081/list_user in the browser, the result is shown in the figure below:

Access http://127.0.0.1:8081/abcd in the browser, the result is shown in the figure below:

Access http://127.0.0.1:8081/abcdefg in the browser, the result is shown in the figure below:


Static Files

Express provides built-in middleware express.static to set static files such as images, CSS, JavaScript, etc.

You can use express.static middleware to set the static file path. For example, if you put images, CSS, and JavaScript files in the public directory, you can write:

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 functionality of handling static files.

Create the express_demo3.js file, the code is as follows:

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 address is 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 the browser (this example uses the Example tutorial logo), the result is shown in the figure below:


GET Method

The following example demonstrates submitting two parameters via the GET method in a form. We can use theprocess_getrouter to handle the input:

index.html file code:

<html> <body> <form action="/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 example, access address is 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 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 the POST method in a form. We can use theprocess_postrouter 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 an 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 example, access address is 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 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:

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 address is 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 the browser, as shown in the figure:

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 Materials

Other extensions