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