Express.js 中的 req.path 屬性
req.path 屬性包含所請求 URL 的路徑部分。此屬性被廣泛地用於跟蹤傳入的請求及其路徑。它主要用於記錄請求。
語法
req.path
示例 1
建立一個名為 "reqPath.js" 的檔案並複製以下程式碼片段。建立檔案後,使用命令 "node reqPath.js" 執行此程式碼,如以下示例所示 −
// req.path Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
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 an endpoint
app.get('/api', function (req, res) {
console.log(req.path);
res.send(req.path);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});用 GET 請求訪問以下端點 − https://:3000/api
輸出
C:\home
ode>> node reqPath.js Server listening on PORT 3000 /api
示例 2
我們來看另一個示例。
// req.path Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
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 an endpoint
app.get('/api/v1/endpoint', function (req, res) {
console.log("Endpoint hit: ", req.path);
res.send(req.path);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});用 GET 請求訪問以下端點 − https://:3000/api/v1/endpoint
輸出
C:\home
ode>> node reqPath.js Server listening on PORT 3000 Endpoint hit: /api/v1/endpoint
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP