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