Latest web development tutorials

Node.js Express framework

Express Profile

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.

Use Express can quickly set up a fully functional website.

Express Frame core features:

  • Middleware can be set to respond to HTTP requests.

  • It defines the routing table for performing different HTTP request action.

  • You can pass parameters to the template to dynamically render HTML pages.


Installation Express

Installation Express and save it to rely on the list:

$ npm install express --save

The above command will Express frame is mountednode_modules directory the current directory, the directory will be created automatically express node_modulesdirectory. Several important needs and express module is installed with the framework:

  • body-parser - node.js middleware, JSON, Raw, Text and URL-encoded data for processing.

  • cookie-parser - This is a tool for parsing Cookie.By req.cookies can get to pass over the cookie, and turn them into objects.

  • multer - node.js middleware for processing enctype = "multipart / form-data " ( set form MIME encoding) form data.

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

The first framework instance Express

Next, we use the Express framework to output "Hello World".

The following example we introduced express module, and the requesting client, the response to "Hello World" string.

Create express_demo.js file, the code is 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)

})

Execute the code above:

$ node express_demo.js 
应用实例,访问地址为 http://0.0.0.0:8081

Access http://127.0.0.1:8081 in the browser, the results as shown below:


Request and Response

Express application uses callback functionparameters: request and responseobjects to handle data requests and responses.

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

introduce specificrequest and responseobject:

Request Object - request object represents an HTTP request contains the request query string parameter, content, HTTP header attributes.Common attributes are:

  1. req.app: When callback to an external file, with access express req.app examples
  2. req.baseUrl: Get URL routing currently installed
  3. req.body / req.cookies: get "request body" / Cookies
  4. req.fresh / req.stale: determine whether the request is still "fresh"
  5. req.hostname / req.ip: obtain the host name and IP address
  6. req.originalUrl: Get the original request URL
  7. req.params: Get route parameters
  8. req.path: Get the request path
  9. req.protocol: Get protocol type
  10. req.query: Get the URL query string parameters
  11. req.route: Get the current matching route
  12. req.subdomains: Get a subdomain
  13. req.accpets (): Check the request header Accept request type
  14. req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages
  15. req.get (): Gets the specified HTTP request header
  16. req.is (): if the request header Content-Type MIME type

Response objects - response object represents an HTTP response, HTTP that is, when receiving a request sent to the client response data. Common attributes are:

  1. res.app: same as req.app
  2. res.append (): Specifies additional HTTP header
  3. res.set () first before res.append () will reset the settings of
  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 (): Specifies the transmission path of the file
  8. res.get (): Returns the HTTP header
  9. res.json (): transfer JSON response
  10. res.jsonp (): transfer JSONP response
  11. res.location (): set the Location HTTP response headers only, not set or close response status code
  12. res.redirect (): set the Location HTTP response headers, and set status code 302
  13. res.send (): HTTP response transfer
  14. res.sendFile (path [, options] [, fn]): Specifies the transmission path of the file - is automatically set Content-Type extension based on file
  15. res.set (): set the HTTP header, you can set multiple incoming object head
  16. res.status (): set the HTTP status code
  17. res.type (): set the Content-Type MIME type

routing

We already know the basic application HTTP requests and route determined by whom (specify a script) to respond to client requests.

In the HTTP request, we can extract the URL routing and GET / POST parameter request.

Next we extend Hello World, to add some features to handle more types of HTTP requests.

Create express_demo2.js file, the code is 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.get('/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)

})

Execute the code above:

$ node express_demo2.js 
应用实例,访问地址为 http://0.0.0.0:8081

Then you can try to access http://127.0.0.1:8081 different address, to see the effect.

Access http://127.0.0.1:8081/list_user in the browser, the results as shown below:

Access http://127.0.0.1:8081/abcd in the browser, the results as shown below:

Access http://127.0.0.1:8081/abcdefg in the browser, the results as shown below:


Static files

Express provides built-in middlewareexpress.static to set static files such as: pictures, CSS, JavaScript and so on.

You can useexpress.static middleware to set a static file path.For example, if you picture, CSS, JavaScript files in the public directory, you can write:

app.use(express.static('public'));

We can go to public / images directory delegated some pictures, as follows:

node_modules
server.js
public/
public/images
public/images/logo.png

Let us modify the next "Hello Word" add application processing functionality static files.

Create express_demo3.js file, the code is 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)

})

Execute the code above:

$ node express_demo3.js 
应用实例,访问地址为 http://0.0.0.0:8081

Execute the code above:


GET Method

The following example demonstrates the two parameters in the form submitted by the GET method, we can use the router server.jsprocess_get within the file to process the input:

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>

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)

})

Execute the code above:

node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Browser access http://127.0.0.1:8081/index.htm, as shown:

Now you can enter data into forms, and submit the following presentation:


POST method

The following example demonstrates two parameters via the POST method to submit the form, we can use the router server.jsprocess_post within the file to process the input:

index.htm file code 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>

server.js file code 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)

})

Execute the code above:

$ node server.js
应用实例,访问地址为 http://0.0.0.0:8081

Browser access http://127.0.0.1:8081/index.htm, as shown:

Now you can enter data into forms, and submit the following presentation:


File Upload

Below we create a form for uploading a file using the POST method, the form enctype attribute set to multipart / form-data.

index.htm file code 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>

server.js file code 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)

})

Execute the code above:

$ node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Browser access http://127.0.0.1:8081/index.htm, as shown:

Now you can enter data into forms, and submit the following presentation:


Cookie Management

We can use the middleware sends cookie information to the Node.js server, the following code outputs the cookie information is 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)

Execute the code above:

$ node express_cookie.js 

Now you can access and view http://127.0.0.1:8081 output terminal information, the following presentation:


Relevant information