Express.js 中的 router.route() 方法


router.route() 方法返回單一路由的例項,該例項可用於進一步處理 HTTP 動詞(帶可選中介軟體)。此方法可用於避免重複的路由命名,因此不會產生型別錯誤。

語法

router.route( path )

示例 1

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

// router.route() 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 a route
router.route('/api')
.get(function (req, res, next) {
   console.log("GET request - /api endpoint 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 請求訪問以下端點 − localhost:3000/api

輸出

C:\home
ode>> node routerRoute.js Server listening on PORT 3000 GET request - /api endpoint is called

示例 2

我們再看一個示例。

// router.route() 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 routings
router.route('/api')
.get(function (req, res, next) {
   console.log("/api -> GET request is called");
   res.end();
})
.post(function (req, res, next) {
   console.log("/api -> POST request is called");
   res.end();
})
.put(function (req, res, next) {
   console.log("/api -> PUT request 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 請求 −localhost:3000/api

  • POST 請求 −localhost:3000/api

  • PUT 請求 −localhost:3000/api

輸出

C:\home
ode>> node routerRoute.js Server listening on PORT 3000 /api -> GET request is called /api -> POST request is called /api -> PUT request is called

更新於: 29-1 月-2022

1K+ 檢視次數

開啟您的 職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.