Express.js 中的 router.all() 方法
router.all() 方法匹配所有 HTTP 方法。此方法主要用于为特定路径前缀和任意匹配映射“全局”逻辑。
语法
router.all( path, [callback, ...] callback )
示例 1
创建一个名为“routerAll.js”的文件并复制以下代码段。创建文件后,使用命令“node routerAll.js”运行此代码,如下面的示例所示 −
// router.all() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Setting the single route in api
router.all('/user', function (req, res) {
console.log("Home Page is called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求访问以下端点 − https://:3000/user
输出
C:\home
ode>> node routerAll.js Server listening on PORT 3000 Home Page is called
示例 2
我们再来看一个示例。
// router.all() Method Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining multiple routes
router.all('/home', function (req, res) {
console.log("Home Page is called");
res.end();
});
router.all('/index', function (req, res) {
console.log("Index Page is called");
res.end();
});
router.all('/api', function (req, res) {
console.log("API Page is called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求逐个访问以下端点 −
https://:3000/home
https://:3000/index
https://:3000/app
输出
C:\home
ode>> node routerAll.js Server listening on PORT 3000 Home Page is called Index Page is called API Page is called
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP