router.all()函數類似於router.METHOD()方法,但它與所有HTTP方法(動詞)匹配。這對於為任意匹配或特定路徑前綴映射全局邏輯非常有幫助。
用法:
router.all(path, [callback, ...] callback)
參數:path參數是指定URL的路徑,而callback是作為參數傳遞的函數。
返回值:它返回響應。
快遞模塊的安裝:
- 您可以訪問安裝Express模塊的鏈接。您可以使用此命令安裝此軟件包。
npm install express
- 安裝Express模塊後,可以使用命令在命令提示符下檢查Express版本。
npm version express
- 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
node index.js
範例1: 文件名:index.js
var express = require('express');
var app = express();
var router = express.Router();
var PORT = 3000;
// Setting single route
router.all('/user', function (req, res) {
console.log("User Page Called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
運行程序的步驟:
- 項目結構將如下所示:
- 確保使用以下命令安裝了Express模塊:
npm install express
- 使用以下命令運行index.js文件:
node index.js
輸出:
Server listening on PORT 3000
- 現在向POST,PUT,DELETE或任何其他類型的請求發出對http://localhost:3000 /user的任何請求,它將顯示以下輸出
User Page Called
對http://localhost:3000 /user的每種請求類型都將打印相同的輸出。
範例2: 文件名:index.js
var express = require('express');
var app = express();
var router = express.Router();
var PORT = 3000;
// Setting multiple routes
router.all('/user', function (req, res) {
console.log("User Page Called");
res.end();
});
router.all('/student', function (req, res) {
console.log("Student Page Called");
res.end();
});
router.all('/teacher', function (req, res) {
console.log("Teacher Page Called");
res.end();
});
app.use(router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
使用以下命令運行index.js文件:
node index.js
現在向http://localhost:3000 /user,http://localhost:3000 /student和http://localhost:3000 /teacher發出GET請求,它將顯示以下輸出。
User Page Called Student Page Called Teacher Page Called
參考: https://expressjs.com/en/4x/api.html#router.all
相關用法
- PHP cos( )用法及代碼示例
- d3.js d3.max()用法及代碼示例
- PHP sin( )用法及代碼示例
- PHP exp()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- d3.js d3.mean()用法及代碼示例
- p5.js mag()用法及代碼示例
- d3.js d3.sum()用法及代碼示例
- p5.js value()用法及代碼示例
- d3.js d3.hsl()用法及代碼示例
- p5.js nfs()用法及代碼示例
- PHP max( )用法及代碼示例
- p5.js nfp()用法及代碼示例
注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js router.all() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。