Express.js 中的 req.route 属性
req.route 属性包含最近匹配的路由的字符串格式。
语法
req.route
示例 1
创建一个名为 “reqRoute.js” 的文件并复制以下代码片段。创建文件后,使用命令 “node reqRoute.js” 运行此代码,如下例所示 −
// req.route Property 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 an endpoint and checking req.route app.get('/api', function (req, res) { console.log(req.route); res.send(); }); 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 reqRoute.js Server listening on PORT 3000 Route { path: '/api', stack: [ Layer { handle: [Function], name: '', params: undefined, path: undefined, keys: [], regexp: /^\/?$/i, method: 'get' } ], methods: { get: true } }
示例 2
我们来看另一个示例。
// req.route Property 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 an endpoint and checking req.route app.get('/api', function (req, res) { console.log("Path is: " + req.route.path); res.send("Path is: "+ req.route.path); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); }); var express = require('express'); var app = express(); var PORT = 3000;
使用 GET 请求访问以下端点:localhost:3000/api
输出
C:\home
ode>> node reqRoute.js Server listening on PORT 3000 Path is: /api
广告