Express.js – app.all() 方法


**app.all()** 方法可用于所有类型的 HTTP 请求路由,例如 POST、GET、PUT、DELETE 等针对任何特定路由的请求。它可以映射所有类型的请求,唯一条件是路由必须匹配。

语法

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

参数

  • **path −** 这是调用中间件函数的路径。路径可以是字符串、路径模式、正则表达式或所有这些的数组。
  • **callback −** 这些是中间件函数或一系列中间件函数,其作用类似于中间件,但这些回调可以调用 next(路由)。

示例 1

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

// app.all() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from 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
ode>> node appAll.js Server listening on PORT 3000 API CALLED

示例 2

让我们再看一个例子。

// app.all() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from 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
ode>> node appPost.js Server listening on PORT 3000 /api called with method: POST /api called with method: PUT /api called with method: GET

更新于: 2021年9月30日

3K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.