Express.js – app.all() 方法

该方法可用于 HTTP 请求的所有类型的路由,即 POST、GET、PUT、DELETE 等,对任何特定路由发出的请求。它可以将应用程序类型的请求映射到路由应该匹配的唯一条件。app.all()

语法

app.path(path, callback, [callback])

参数

  • path -这是调用中间件函数的路径。路径可以是字符串、路径模式、正则表达式或所有这些的数组。

  • callback -这些是中间件函数或一系列中间件函数,它们的作用类似于中间件,但这些回调可以调用 next(路由)。

示例 1

创建一个名为“ appAll.js ”的文件并复制以下代码片段。创建文件后,使用命令“ node appal.js ”运行此代码。

// app.all() 方法演示示例

// 导入 express 模块
const express = require('express');

// 初始化 express 和端口号
var app = express();

// 从 express 初始化路由器
var router = express.Router();
var PORT = 3000;

app.all('/api', function (req, res, next) {
   console.log('API CALLED');
   next();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

点击以下任意端点,响应仍将相同。

输出结果

C:\home\node>> node appAll.js
Server listening on PORT 3000
API CALLED

示例 2

让我们再看一个例子。

// app.all() 方法演示示例

// 导入 express 模块
const express = require('express');

// 初始化 express 和端口号
var app = express();

// 从 express 初始化路由器
var router = express.Router();
var PORT = 3000;

app.all('/api', function (req, res, next) {
   console.log('/api called with method: ', req.method);
   next();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

依次点击以下端点以获取响应

输出结果

C:\home\node>> node appPost.js
Server listening on PORT 3000
/api called with method: POST
/api called with method: PUT
/api called with method: GET