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.