Node .js Express framework
Express is a web development framework designed .js Node platform, which is based on the nodejs platform.
Introduction to Express
Express is a simple and flexible node.js web application framework that provides a range of powerful features to help you create a variety of web applications and rich HTTP tools.
Express allows you to quickly build a fully functional website.
The core features of the Express framework include:
-
Middleware can be set up in response to HTTP requests.
-
A routing table is defined to perform different HTTP request actions.
-
HTML pages can be rendered dynamically by passing parameters to the template.
Install Express
Install Express and save it to the dependency list:
$ npm 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 in the current directory. The following important modules need to be installed with the express framework:
-
Body-parser-node .js middleware for processing JSON, Raw, Text, and URL encoded data.
-
cookie-parser - This is a tool for parsing cookies. Req.cookies allow you to get passed cookies and turn them into objects.
-
Multer - node .js middleware for processing form data for the enctype "multipart/form-data" (setting up the MIME encoding of the form).
$ npm install body-parser --save $ npm install cookie-parser --save $ npm install multer --save
The first instance of the Express framework
Next, we use the Express framework to output Hello World.
In the following example, we introduced the express module and responded to the Hello World string after the client initiated the request.
Create express_demo.js file, as follows:
//express_demo.js 文件 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("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
$ node express_demo.js 应用实例,访问地址为 http://0.0.0.0:8081
Access the browser and http://127.0.0.1:8081 as shown in the following image:
Requests and responses
Express apps use parameters of callback functions: request and response objects to process request and response data.
app.get('/', function (req, res) { // -- })
A specific description of the request and response objects:
The Request object - The request object represents an HTTP request and contains properties such as request query strings, parameters, content, HTTP header, and so on. C ommon properties are:
- req.app: When callback is an external file, use the req.app to access the express instance
- req.baseUrl: Gets the URL path for the current installation of the route
- req.body / req.cookies: Get "request subject" / cookies
- req.fresh / req.stale: Determine whether the request is still "fresh"
- req.hostname / req.ip: Get the host name and IP address
- req.originalUrl: Get the original request URL
- req.params: Get the parameters for the route
- req.path: Get the request path
- req.protocol: Get the protocol type
- req.query: Get a string of query parameters for the URL
- req.route: Gets the currently matched route
- req.subdomains: Get subdomains
- req.accpets(): Check the type of request for the requested Access header
- req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages
- req.get(): Get the specified HTTP request header
- req.is (): Determine the MIME type of the request headerContent-Type
The Response object - The response object represents the HTTP response, which is the HTTP response data sent to the client when the request is received. Common properties are:
- res.app: It'req.app the same
- res.append(): Append the specified HTTP header
- Res.set() resets the previously set header after res.append().
- res.cookie (name, value, option): Set cookies
- opition: domain / expires / httpOnly / maxAge / path / secure / signed
- res.clear cookies (): Clear cookies
- res.download(): Transfer the file for the specified path
- res.get(): Returns the specified HTTP header
- res.json(): Transmit the JSON response
- res.jsonp(): Transmit the JSONP response
- res.location(): Set only the response's Location HTTP header, no status code or close response
- res.redirect(): Set the Response Location HTTP header and set the status code 302
- res.send(): Transmit the HTTP response
- res.sendFile (path , options , fn) : Transfer a file with a specified path - Automatically set Content-Type based on the file extension
- res.set(): Set http headers, and incoming objects can set multiple heads at once
- res.status(): Set the HTTP status code
- res.type(): Set the MIME type of Content-Type
Routing
We've seen the basic application of HTTP requests, and routing determines who (the specified script) responds to client requests.
In HTTP requests, we can route out the URL of the request and the GET/POST parameters.
Next, let's extend Hello World to add features to handle more types of HTTP requests.
Create express_demo2.js file, as follows:
var express = require('express'); var app = express(); // 主页输出 "Hello World" app.get('/', function (req, res) { console.log("主页 GET 请求"); res.send('Hello GET'); }) // POST 请求 app.post('/', function (req, res) { console.log("主页 POST 请求"); res.send('Hello POST'); }) // /del_user 页面响应 app.delete('/del_user', function (req, res) { console.log("/del_user 响应 DELETE 请求"); res.send('删除页面'); }) // /list_user 页面 GET 请求 app.get('/list_user', function (req, res) { console.log("/list_user GET 请求"); res.send('用户列表页面'); }) // 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求 app.get('/ab*cd', function(req, res) { console.log("/ab*cd GET 请求"); res.send('正则匹配'); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
$ node express_demo2.js 应用实例,访问地址为 http://0.0.0.0:8081
Next you can try to http://127.0.0.1:8081 different addresses to see how it works.
Access the browser and the http://127.0.0.1:8081/list_user as shown in the following image:
The browser accesses the http://127.0.0.1:8081/abcd, as shown in the following image:
Access the browser and the http://127.0.0.1:8081/abcdefg as shown in the following image:
Static file
Express provides built-in middleware express.static to set static files such as: Pictures, CSS, JavaScript, etc.
You can use the express.static middleware to set the static file path. For example, if you put pictures, CSS, JavaScript files in the public directory, you can write this:
app.use(express.static('public'));
We can drop some pictures into the public/images directory, as follows:
node_modules server.js public/ public/images public/images/logo.png
Let's modify the Hello Word app to add the ability to work with static files.
Create an Express_Demo3.js file, the code as follows:
var express = require('express'); var app = express(); app.use(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("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
$ node express_demo3.js 应用实例,访问地址为 http://0.0.0.0:8081
To execute the above code:
Access to the browser http://127.0.0.1:8081/images/logo.png (this example uses the logo of the W3Cschool tutorial), as shown in the following image:
GET method
The following example demonstrates that two parameters are submitted through the GET method in a form, and we can use the .js router in the server process_get file to process the input:
The index .htm file code is as follows:
<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>
The server .js file code is as follows:
var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.get('/process_get', function (req, res) { // 输出 JSON 格式 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("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
node server.js 应用实例,访问地址为 http://0.0.0.0:8081
Browser access http://127.0.0.1:8081/index.htm, as shown in the figure:
Now you can enter data into the form and submit it, as follows:
POST method
The following example demonstrates that two parameters are submitted through the POST method in a form, and we can use the .js router in the server process_post file to process the input:
The index .htm file code is modified as follows:
<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>
The server.js file code is modified as follows:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // 创建 application/x-www-form-urlencoded 编码解析 var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static('public')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/process_post', urlencodedParser, function (req, res) { // 输出 JSON 格式 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("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
The browser accesses http://127.0.0.1:8081/index.htm, as shown in the figure:
Now you can enter data into the form and submit it, as follows:
File upload
Below we create a form for uploading files, using the POST method, the form enctype property is set to multipart/form-data.
The index .htm file code is modified as follows:
<html> <head> <title>文件上传表单</title> </head> <body> <h3>文件上传:</h3> 选择一个文件上传: <br /> <form action="/file_upload" method="post" enctype="multipart/form-data"> <input type="file" name="image" size="50" /> <br /> <input type="submit" value="上传文件" /> </form> </body> </html>
The server.js file code is modified as follows:
var express = require('express'); var app = express(); var fs = require("fs"); var bodyParser = require('body-parser'); var multer = require('multer'); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(multer({ dest: '/tmp/'}).array('image')); app.get('/index.htm', function (req, res) { res.sendFile( __dirname + "/" + "index.htm" ); }) app.post('/file_upload', function (req, res) { console.log(req.files[0]); // 上传的文件信息 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("应用实例,访问地址为 http://%s:%s", host, port) })
To execute the above code:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
The browser accesses http://127.0.0.1:8081/index.htm, as shown in the figure:
Now you can enter data into the form and submit it, as follows:
Cookie management
We can use middleware to send .js cookie information to the Node server, and the following code outputs the cookie information sent by the client:
// express_cookie.js 文件 var express = require('express') var cookieParser = require('cookie-parser') var app = express() app.use(cookieParser()) app.get('/', function(req, res) { console.log("Cookies: ", req.cookies) }) app.listen(8081)
To execute the above code:
$ node express_cookie.js
Now you can access http://127.0.0.1:8081 and view the output of the terminal information, as shown below: