preface

Express and Koa are currently the most popular Node-based Web development frameworks, and they have the same developers. Koa seems to be more popular now because we can do secondary development on Koa, and this article focuses on Express.

Common functions of Express

  • Routing control
  • The middleware
  • Static file service
  • The template parsing

Method of use

Here are some common apis:

First reference Express, and execute

let express = require('express');
let app = express();
app.listen(8080, () = > {console.log(8080)});Copy the code

1. app[method](path, function(req, res){})

Requests such as GET from clients are processed based on the request path. The first argument, Path, is the path to the request, and the second argument is the callback function that handles the request.

app.get('/'.function (req, res) {
    res.end('ok');
});

Copy the code

2 app.use([path,] function [, function...] )

Middleware is a function that processes HTTP requests for specific tasks, such as checking whether the user is logged in, checking whether the user has access rights, and so on. If path is not written, the default is “/”, and note that middleware execution is sequential

The functions put into app.use are called middleware functions and generally have three characteristics:

  • Requests and responses can be processed by one middleware and then passed to the next middleware.
  • The next argument to the callback function accepts calls from other middleware, and next() in the function body continues to pass the request data.
  • Middleware that return execution can be differentiated based on the path.
Next is also a function that means that the current middleware has finished executing and can move on to other middleware
app.use(function (req, res, next) {
    res.setHeader('Content-Type'.'text/html; charset=utf8');
    console.log('Middleware without paths');
    // If you pass an arbitrary argument when calling next, this function is in error.
    // Express then skips all subsequent middleware and routing
    // Pass it to the error-handling middleware
    next('I was wrong');
});
app.use('/user1'.function (req, res, next) {
    console.log('user1')
    next()
});
app.use('/user2'.function (req, res, next) {
    console.log('user2')
    res.end('user2');
});
Error handling middleware has four parameters
app.use('/hello'.function (err, req, res, next) {
    res.end('hello ' + err);
});
Copy the code

If something goes wrong, it goes directly to the error-handling middleware to handle it.

4.app.param(paramName, callback)

Used to batch process parameters in a path

app.get('/username/:userid/:name'.function (req, res) {
    res.end(req.params.name+req.params.name);
});
app.param('userid'.function(req,res,next,userid,name){
    next();
})
Copy the code

5. app.set(key, val)

Used to set parameters, such as render templates

app.set('views', path.resolve(path.join(__dirname, 'views')));
app.set('view engine'.'html');
Copy the code

6.app.engin()

Specifies how the file will be rendered

app.engine('html',html);
Copy the code

The principle of Express

Focus on the routing function

Routing and middleware, you need to have a place to store that information, like routing information, like middleware callback functions and so on. Express has an object called Router that stores middleware objects, and it has an array called stack that stores all of the middleware objects, and the middleware objects are Layer objects.

app.use([path,] function [, function…] ),

app.use([path,] function [, function…] ),

app.use… The functions in parentheses represent layer1 and layer2, so they should be executed layer by layer.

Rouer and Route

  • RouteThe main purpose of the object is to create a routing middleware and create multiple methodslayerSave to your ownstackIn the array
  • RouterThe main purpose of the object is to create a guide for generic or routing middlewareLayerObject link back to onerouteObject) and then save it in your ownstackIn the array.

The resources

According to the source code simulation express framework common functions

Express working principle and source code analysis 1: create a route