[Nodejs] Basic use of Express

insert image description here

Express Chinese website

Based on the Node.js platform, a fast, open and minimal web development framework.

1. How to install Express


The installation of Express can directly use the project on the npm package manager. Before installing npm, you can install the Taobao image first:
npm install -g cnpm --registry=https://registry.npmmirror.com/

In this way, we use cnpm instead of npm, which makes the download speed much faster; secondly, you need to run the following command in your project directory to initialize npm, and press enter for all prompts, which will generate package.json, which is used for describing project files.

cnpm init

re-enter

cnpm install

Now there will be another node_modules folder in the project directory, which contains the modules provided by node.js, but of course there is no such folder now. The next step is to actually install express, execute:

cnpm install express --save

At this time, we see that there are many different versions of application folders in the node_modules folder, and then execute

express --version

Check whether express is installed successfully. If the version number is displayed, the installation is correct.

4.16.1

2. Operating principle


Bottom layer: http module

The Express framework is built on top of node.js' built-in http module. The original code for generating the server by the http module is as follows

var http = require("http");

var app = http.createServer(function(request, response) {
    
    
  response.writeHead(200, {
    
    "Content-Type": "text/plain"});
  response.end("Hello world!");
});

app.listen(3000, "localhost");

The core of the Express framework is the repackaging of the http module. The above code can be rewritten in Express as follows

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    
    
  res.send('Hello world!');
});

app.listen(3000);

The Express framework is equivalent to adding an intermediate layer on top of the http module

what is middleware

  • Simply put, middleware is a function that handles HTTP requests. Its biggest feature is that after one middleware is processed, it is passed to the next middleware. When the App instance is running, it will call a series of middleware.
    Each middleware can receive three parameters from the App instance, which are request object (representing HTTP request), response object (representing HTTP response), next callback function ( represents the next middleware). Each middleware can process the HTTP request (request object), and decide whether to call the next method, and pass the request object to the next middleware.
  • A middleware that does nothing and only passes the request object is as follows
function uselessMiddleware(req, res, next) {
    
    
  next();
}
  • The next of the above code is the next middleware. If it has a parameter, it means throw an error, the parameter is the error text
  • After an error is thrown, the following middleware will not execute until an error handling function is found
function uselessMiddleware(req, res, next) {
    
    
  next('出错了!');
}

3. Express method


Introduction to Express Routing

Routes represent the definition of application endpoints (URIs) and how to respond to client requests. It contains a function (callback) when the requester (methods), path (path) and route match;

app.methods(path, callback);

Express Routing Method

The Express method is derived from one of the HTTP methods, attached to an instance of the express class. The methods it can request include:
get、post、put、head、delete、options、trace、copy、lock、mkcol、move、purge、propfind、proppatch、unlock、report、mkactivity、checkout、merge、m-search、notify、subscribe、unsubscribe、patch、search 和 connect.

Routing refers to how to define application endpoints (URIs) and how to respond to client requests.
Routing is composed of a URI, HTTP request (GET, POST, etc.) and several handles, its structure is as follows: app.METHOD(path, [callback…], callback), app is an instance of express object, METHOD is an The HTTP request method, path is the path on the server, and callback is the function to execute when the route is matched.

Here is a basic routing example:

var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
    
    
  //写完一个send,后面所有跟路由有关的都不会执行
  //会自动响应对应的数据类型
  //   res.send([1, 2, 3]);
  //   res.send({ ok: 1 });
  //   res.json({ ok: 1 });
   // 使用混合使用函数数组处理时如果前面有res.send();那么后面和路由处理相关代码都不生效
  res.send('hello world');
  res.send(`
        <html>
            <h1>hello world</h2>
        </html>
    `);
});

The route path and the request method together define the endpoint of the request, which can be a string, a string pattern, or a regular expression.

all method and HTTP verb method

For different requests, Express provides some aliases for the use method. For example, the above code can also be written in the form of an alias

var express = require("express");
var http = require("http");
var app = express();

app.all("*", function(request, response, next) {
    
    
  response.writeHead(200, {
    
     "Content-Type": "text/plain" });
  next();
});

app.get("/", function(request, response) {
    
    
  response.end("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
    
    
  response.end("Welcome to the about page!");
});

app.get("*", function(request, response) {
    
    
  response.end("404!");
});

http.createServer(app).listen(1337);
  • The all method of the above code means that all requests must pass through the middleware, and the "*" in the parameter means that it is valid for all paths. The get method is that only the HTTP request of the GET verb passes through the middleware, and its first parameter is the path of the request. Since the callback function of the get method does not call the next method, as long as one middleware is called, the subsequent middleware will not be called again
  • In addition to the get method, Express also provides post, put, delete methods, that is, HTTP verbs are Express methods
  • In addition to the get method, Express also provides post, put, delete methods, that is, HTTP verbs are Express methods
  • The first parameter of these methods is the path of the request. Express allows pattern matching in addition to absolute matching
app.get("/hello/:who", function(req, res) {
    
    
  res.end("Hello, " + req.params.who + ".");
});

4. Path matching


4.1 String path

// 匹配根路径的请求
app.get('/', function (req, res) {
    
    
  res.send('root');
});

// 匹配 /about 路径的请求
app.get('/about', function (req, res) {
    
    
  res.send('about');
});

// 匹配 /random.text 路径的请求
app.get('/random.text', function (req, res) {
    
    
  res.send('random.text');
});

4.2 String Pattern Paths

Example of a route path using a string pattern:

// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
    
    
  res.send('ab?cd');
});

// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
    
    
  res.send('ab+cd');
});

// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function(req, res) {
    
    
  res.send('ab*cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
    
    
 res.send('ab(cd)?e');
});

4.3 Regular expression paths

Example routing path using regular expressions:

// 匹配任何路径中含有 a 的路径:
app.get(/a/, function(req, res) {
    
    
  res.send('/a/');
});

// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等
app.get(/.*fly$/, function(req, res) {
    
    
  res.send('/.*fly$/');
});

Multiple callback functions can be provided for request processing, which behave like middleware. The only difference is that these callbacks may call the next('route') method while bypassing other route callbacks. This mechanism can be used to define preconditions for a route, and if it does not make sense to continue on an existing path, control can be passed to the remaining path.

app.get('/example/a', function (req, res) {
    
    
  res.send('Hello from A!');
});

Use multiple callback functions to handle routing (remember to specify the next object):

app.get('/example/b', function (req, res, next) {
    
    
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
    
    
  res.send('Hello from B!');
});

Handle routing with an array of callback functions:

var cb0 = function (req, res, next) {
    
    
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
    
    
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
    
    
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])

5. response object


method describe
res.download() Prompt for files to download.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send JSON responses with JSONP support.
res.redirect() Redirect request.
res.render() Render the view template.
res.send() Send various types of responses.
res.sendFile() Send the file as an octet stream.
res.sendStatus() Sets the response status code and sends its string representation as the response body.

Example:
(1) response.redirect method

The response.redirect method allows URL redirection

response.redirect("/hello/anime");
response.redirect("http://www.example.com");
response.redirect(301, "http://www.example.com"); 

(2) response.sendFile method

The response.sendFile method is used to send files

response.sendFile("/path/to/anime.mp4");

(3) response.render method

The response.render method is used to render the web page template.

//  使用render方法,将message变量传入index模板,渲染成HTML网页
app.get("/", function(request, response) {
    
    
  response.render("index", {
    
     message: "Hello World" });
});

6. Route Handler


You can provide multiple callback functions that behave like middleware to handle requests. The only exception is that these callbacks may call next('route') to bypass the rest of the routing callbacks. You can use this mechanism to impose preconditions on routes and then pass control to subsequent routes if there is no reason to continue using the current route.

Multiple callback functions can handle a route (make sure to specify the next object). For example:

app.get('/example/b', function (req, res, next) {
    
    
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
    
    
  res.send('Hello from B!')
})

Mixing functions and arrays of functions for routing:

const fun1 = (req, res, next) => {
    
    
  // 验证用户token过期, cookie过期
  console.log('token验证');
  let isValid = true;
  if (isValid) {
    
    
    next();
  } else {
    
    
    //将第一个中间件的数据传输到第二个中间件
    res.name = "dselegent";
    res.send('error');
  }
};
const fun2 = (req, res) => {
    
    
   console.log(res.name)
  res.send('home');
};
app.get('/home', [fun1, fun2]);

app.get('/list', fun1, (req, res) => {
    
    
  res.send('list');
});

7. Middleware


Express is a web development framework with minimal functions, which is completely composed of routing and middleware: in essence, an Express application is calling various middleware.

Middleware (Middleware) is a function that can access the request object (request object (req)), the response object (response object (res)), and the middleware in the request-response loop process in the web application, generally named A variable for next.

Middleware functions include:

  • execute any code.
  • Modify request and response objects.
  • End the request-response loop.
  • The next middleware in the call stack.

If the current middleware does not terminate the request-response loop, the next() method must be called to pass control to the next middleware, otherwise the request will hang.

Express applications can use the following middleware:

  • application-level middleware
  • Router-level middleware
  • error handling middleware
  • built-in middleware
  • third party middleware

Middleware can be mounted at the application level or at the route level using an optional mount path. In addition, you can also mount a series of middleware functions at the same time, thus creating a sub-middleware stack on a mount point.

7.1 Application-level middleware

Application-level middleware is bound to the app object using app.use() and app.METHOD(), where METHOD is the method of the HTTP request that needs to be processed, such as GET, PUT, POST, etc., all lowercase. For example:

var app = express()
const indexRouter = require('./route/indexRouter');
const LoginRouter = require('./route/LoginRouter');

//应用级别(后面的路由都会执行此中间件)
app.use((req, res, next) => {
    
    
  // 验证用户token过期, cookie过期
  console.log('token验证');
  let isValid = true;
  if (isValid) {
    
    
    next();
  } else {
    
    
    res.send('error');
  }
});

//应用级别(这里不写路径默认/)
//这些use方法是每次访问都是从上往下执行
//如果是/login/a,会先找到/login开头的这个应用级中间件
//然后再进入这个中间件找/a
app.use(indexRouter);
app.use('/login', LoginRouter);

7.2 Router-level middleware

(1) app.route()
You can use app.route() to create chainable route handlers for route paths. Since paths are specified in a single place, creating modular routes is very helpful, as is reducing redundancy and typos. For more information on routing see: Router() documentation .

Here's an example app.route() using the chained route handlers defined.

app.route('/book')
  .get(function (req, res) {
    
    
    res.send(' Get a random book')
  })
  .post(function (req, res) {
    
    
    res.send('Add a book')
  })
  .put(function (req, res) {
    
    
    res.send('Update the book')
  })

(2) Express Router
Routing-level middleware is the same as application-level middleware, except that the object it is bound to is express.Router().

Use the express.Router class to create modular, installable route handlers. A Router instance is a complete middleware and routing system; therefore, it is often referred to as a "mini-application".

The following example creates the router as a module, loads the middleware functionality in it, defines some routes, and installs the router module on the main application's path.

home.js creates a router file in the app directory called:var router = express.Router()

var app = express()
var router = express.Router()

// 没有挂载路径的中间件,通过该路由的每个请求都会执行该中间件
router.use(function (req, res, next) {
    
    
  console.log('Time:', Date.now())
  next()
})

// 一个中间件栈,显示任何指向 /user/:id 的 HTTP 请求的信息
router.use('/user/:id', function(req, res, next) {
    
    
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
    
    
  console.log('Request Type:', req.method)
  next()
})

// 一个中间件栈,处理指向 /user/:id 的 GET 请求
router.get('/user/:id', function (req, res, next) {
    
    
  // 如果 user id 为 0, 跳到下一个路由
  if (req.params.id == 0) next('route')
  // 负责将控制权交给栈中下一个中间件
  else next() //
}, function (req, res, next) {
    
    
  // 渲染常规页面
  res.render('regular')
})

// 处理 /user/:id, 渲染一个特殊页面
router.get('/user/:id', function (req, res, next) {
    
    
  console.log(req.params.id)
  res.render('special')
})

module.exports=  router

Then, load the router module in your application:

var indexRouter = require('./home')
// ...
app.use('/home', index)

The app will now be able to handle /homerequests to and/home/user/123456

(3) router.route method
The route method of the router instance object can accept the access path as a parameter

var router = express.Router();

router.route('/api')
	.post(function(req, res) {
    
    
		// ...
	})
	.get(function(req, res) {
    
    
		Bear.find(function(err, bears) {
    
    
			if (err) res.send(err);
			res.json(bears);
		});
	});

module.exports=  router

7.3 Error handling middleware

Error handling middleware is defined similarly to other middleware, except that it takes 4 parameters instead of 3, and its signature is as follows: (err, req, res, next).

//上面的中间件都没有匹配就会走这里
app.use(function(err, req, res, next) {
    
    
  console.error(err.stack)
     //send的状态码默认是200
  res.status(500).send('error')
})

7.4 Built-in middleware

express.static is the only built-in middleware for Express. It is based on serve-static and is responsible for serving static resources in Express applications. Each application can have multiple static directories.

app.use(express.static('public'))
app.use(express.static('uploads'))
app.use(express.static('files'))

7.5 Third-party middleware

Install the node module of the required function and load it in the application, either at the application level or at the routing level.

The following example installs and loads a middleware that parses cookies:cookie-parser

$ npm install cookie-parser
var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')

// 加载用于解析 cookie 的中间件
app.use(cookieParser())

8. Get parameters


8.1 req.query

req.query() can be used to obtain the parameters spliced ​​after the link "?" in the interface request. It is mainly used for get requests and post requests are also applicable. req.query() is natively supported by express, and will automatically convert the parameters into objects and return them.
ask:

http://localhost:5050/server?p=user&q=password

express interface:

let express = require('express')
let server = express()
server.get('/server',(req,resp)=>{
    
    
    console.log(req.query);
    resp.send('')
})
server.listen(5050,()=>{
    
    
    console.log('服务器已就绪')
})

Result after request:
insert image description here

8.2 req.params

req.params()Some special, it is suitable for passing data parameters on the url link, and requires ==:变量名==the writing method used by the background interface to initiate the request.

ask:

http://localhost:5050/nums/1000

express interface:

let express = require('express')
let server = express();
server.get('/nums/:num', (req, resp) => {
    
    
  console.log(req.params);
  resp.send('')
})
server.listen(5050, () =>{
    
    
	 console.log('服务器已就绪')
})

Result after request:
insert image description here

8.3 req.body

req.body() is supported by native express, you can directly use req.body() to get the form data of the post request.

ask:

fecth('http://localhost:5050/people',{
    
    
    method: 'post',
    headers: {
    
    
        'Content-Type': 'application/json'
    },
    body:{
    
    name: 'zhangsan', age: 15}
})

express interface:

const express = require('express');
const server = express();
//配置解析post参数的-不用下载第三方 ,内置
//解析post参数-(url-ky格式) username=kerwin&password=1234
// app.use(express.urlencoded({ extended: false }));
//解析post参数-(json字符串) {name:"",age:100}
app.use(express.json());
server.post('/people', (req, resp) => {
    
    
  console.log(req.body);
  resp.send('')
})
server.listen(5050, () => console.log('服务器已就绪'))

insert image description here

9. Host static files with Express


Express built-in express.static can conveniently host static files, such as images, CSS, JavaScript files, etc.

Pass the directory where the static resource file is located as a parameter to the express.static middleware to provide access to the static resource file. For example, assuming you put images, CSS and JavaScript files in the public directory, you can:

//直接将public里的index.html当成/的网页
app.use(express.static('public'))

Now, the files under the public directory can be accessed.

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

All file paths are relative to the storage directory, so the directory name of the static file will not appear in the URL.

If your static resources are stored in multiple directories, you can call express.static middleware multiple times:

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

When accessing static resource files, the express.static middleware will look for the required files according to the order in which the directories are added.

If you want all files accessed through express.static to be stored under a "virtual" directory (that is, the directory does not exist at all), you can achieve this by specifying a mount path for the static resource directory, as shown below :

app.use('/static', express.static('public'))

Now, you can access the files under the public directory through the address prefixed with "/static".

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

Summarize

app.use(express.static('public'))
<link rel="stylesheet" href="/css/index.css" />
    
app.use('/static', express.static('public'))
<link rel="stylesheet" href="/static/css/index.css" />

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131920866