Express.js – app.route() 方法


app.route() 方法返回單個路由的例項。該單個路由用於處理帶可選中介軟體的 HTTP 動詞。該方法主要用於避免重複名稱。

語法

app.route( )

示例 1

建立一個名為 "appRoute.js" 的檔案,並複製以下程式碼段。建立檔案後,使用命令 "node appRoute.js" 執行此程式碼。

// app.route() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a get, post & other requests
app.route('/user')
.get((req, res, next) => {
   res.send('GET is called');
   console.log('GET is called');
})

.post((req, res, next) => {
   res.send('POST is called');
   console.log('POST is called')
})
.all((req, res, next) => {
   res.send('All others are called');
   console.log('All others are called')
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

點選以下端點/API 訪問上述函式 −

輸出

C:\home
ode>> node appRoute.js '' '/api' '/api/v1'

示例 2

我們再來看一個示例。

// app.route() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating a get, post & other requests
app.route('/api/*')
.get((req, res, next) => {
   res.send('GET is called');
   console.log('GET is called');
})

.post((req, res, next) => {
   res.send('POST is called');
   console.log('POST is called')
})

.all((req, res, next) => {
   res.send('All others are called');
   console.log('All others are called')
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

對於上述函式,可以在 /api/ 後訪問任何端點,它只會透過上述函式。例如,

輸出

C:\home
ode>> node appRoute.js Server listening on PORT 3000 All others are called GET is called

更新時間: 2021 年 9 月 30 日

1K+ 瀏覽次數

助您 職業生涯更上一層樓

完成課程獲得認證

立即開始
廣告
© . All rights reserved.