Node.js Express framework

Posted by dacs on Sun, 06 Mar 2022 05:11:22 +0100

1, Introduction to Express

Express is a simple and flexible node JS Web application framework provides a series of powerful features to help you create various Web applications and rich HTTP tools.
Using Express, you can quickly build a fully functional website.
Core features of Express framework:

  • Middleware can be set up to respond to HTTP requests.
  • The routing table is defined to perform different HTTP request actions.
  • You can render HTML pages dynamically by passing parameters to the template.

2, Install Express

# Install Express and save it to the dependency list
cnpm install express --save

The above command will install the express framework on the node of the current directory_ In the modules directory, node_ The express directory will be automatically created under the modules directory. The following important modules need to be installed with the express framework:

  • body-parser - node.js middleware is used to process JSON, Raw, Text and URL encoded data.
  • Cookie Parser - this is a tool for parsing cookies. Through req Cookies can take the cookies passed in and turn them into objects.
  • multer - node.js middleware is used to process the form data of enctype = "multipart / form data" (set the MIME code of the form).
cnpm install body-parser --save
cnpm install cookie-parser --save
cnpm install multer --save

3, Express framework instance

// Use the Express framework to output "Hello World".
// The following example introduces the express module, which responds to the "Hello World" string after the client initiates the request.
// Create express_demo.js file, the code is as follows:
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: http://%s:%s", host, port)
 
})

// Access in browser http://127.0.0.1:8081
// result
Hello World

4, Request and response

The Express application uses the parameters of the callback function: req(request) and res(response) objects to process the data of the request and response.
app.get('/', function (req, res) {
// –
})

4.1 Request object

Request object - the request object represents the HTTP request, including the request query string, parameters, content, HTTP header and other attributes. Common attributes are:

  • req.app: when the callback is an external file, use req App access instance of express
  • req. URL to get the route of the current installation: baseurl
  • req.body / req.cookies: obtain "request subject" / cookies
  • req.fresh / req.stale: judge whether the request is still "fresh"
  • req.hostname / req.ip: get host name and IP address
  • req.originalUrl: get the original request URL
  • req. Parameters: get the parameters of the route
  • req.path: get request path
  • req.protocol: get protocol type
  • req.query: get the query parameter string of the URL
  • req.route: get the current matching route
  • req.subdomains: get subdomains
  • req. Accept(): check the document type of the acceptable request
  • req.acceptsCharsets / req.acceptsEncodings / req.acceptsLanguages: returns the first acceptable character encoding of the specified character set
  • req.get(): get the specified HTTP request header
  • req.is(): determine the MIME type of the content type of the request header

4.2 Response object

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

  • res.app: the same as req Like app
  • res.append(): append the specified HTTP header
  • res.set() resets the previously set header after res.append()
  • res.cookie(name, value [, option]): set the Cookie
  • opition: domain / expires / httpOnly / maxAge / path / secure / signed
  • res.clearCookie(): clear cookies
  • res.download(): transfer the files in the specified path
  • res.get(): returns the specified HTTP header
  • res.json(): send JSON response
  • res.jsonp(): send JSONP response
  • res.location(): only set the Location HTTP header of the response, not the status code or close response
  • res.redirect(): set the Location HTTP header of the response and the status code 302
  • Res.render (view, [locales], callback): render a view and pass the rendered string to callback. If an error occurs during rendering, next(err) will be called automatically. The callback will be passed in a possible error and the rendered page, so it will not be output automatically.
  • res.send(): send HTTP response
  • res.sendFile(path [, options] [, fn]): transfer the file with the specified path - the content type will be automatically set according to the file extension
  • res.set(): set HTTP headers. Multiple headers can be set for incoming object s at one time
  • res.status(): sets the HTTP status code
  • res.type(): sets the MIME type of content type

5, Routing

We have learned the basic application of HTTP requests, and routing determines who (specifies the script) responds to client requests.
In the HTTP request, we can extract the request URL and GET/POST parameters through routing.
Next, expand Hello World and add some functions to handle more types of HTTP requests.
Create express_demo2.js file, the code is as follows:

var express = require('express');
var app = express();
 
//  Home page output "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 response 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 matching');
})
 
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("Application instance, access address: http://%s:%s", host, port)
 
})

// You can try to access http://127.0.0.1:8081 Different addresses to see the effect.
// Access in browser http://127.0.0.1:8081/list_user
// Access in browser http://127.0.0.1:8081/abcd
// Access in browser http://127.0.0.1:8081/abcdefg

6, Static file

Express provides a 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 pictures, CSS and JavaScript files in the public directory, you can write:
app.use('/public', express.static('public'));
Put some files in the public/images directory, as shown below:
node_modules
server.js
public/
public/images
public/images/logo.png

// Processing static files
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: http://%s:%s", host, port)
 
})

// Access in browser http://127.0.0.1:8081/public/images/logo.png

7, GET method

The following example demonstrates submitting two parameters through the GET method in a form, using server Process in JS file_ GET router to process input:

<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>
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: http://%s:%s", host, port)
 
})

// Browser access http://127.0.0.1:8081/index.html

8, POST method

The following example demonstrates submitting two parameters through the POST method in a form, using server Process in JS file_ Router POST to process input:

<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>
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
 
// Create application/x-www-form-urlencoded encoding resolution
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: http://%s:%s", host, port)
 
})

// Browser access http://127.0.0.1:8081/index.html

9, File upload

Let's create a form for uploading files, use the POST method, and set the enctype attribute of the form to multipart / form data.

<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>
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: http://%s:%s", host, port)
 
})

10, Cookie management

// Use middleware to send data to node JS server sends cookie information. The following code outputs the cookie information sent by the client
// 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)

Topics: node.js Linux kafka Back-end