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);
});点击以下任何一个端点,响应将保持不变。
- **POST –** https://:3000/api
- **GET –** https://:3000/api
- **DELETE –** https://:3000/api
- **PUT –** https://:3000/api
输出
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);
});按顺序点击以下端点以获取响应
- POST – https://:3000/api
- PUT – https://:3000/api
- GET – https://:3000/api
输出
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP