[英]How can i get the name of this JSON or get the path from NodeJS Express Router?
我正在嘗試將命名路由器功能添加到 NodeJS 的快速路由器(這是一種做法,我不想下載任何其他包),我已經成功了,但只剩下一件事......路徑,我的意思是,如果我有這樣的路線:
index.js
const express = require('express');
const app = express();
app.use(require('./routes'));
路線/index.js
const express = require('express');
const expressRouter = express.Router();
const router = require("./namedRoutes")(expressRouter); // <- This is my own named router
const ViewsController = require('../app/controllers/ViewsController');
router.get("/", ViewsController.loadHome).setName("home");
router.get("/fromHome", ViewsController.loadHome).setName("fromHome");
module.exports = router;
我可以使用以下方法從我的助手(車把)中獲取路線名稱:
{{ route "home" }}
或{{ route "fromHome" }}
它返回給我:
localhost:3000/
或localhost:3000/fromHome
但是當我嘗試在 mi index.js上使用此語法添加路徑時
app.use("/other/path", require('./routes'));
我的命名路由將再次返回我localhost:3000/
或localhost:3000/fromHome
而沒有路徑。
在我的路由助手中進行測試,我看到我可以獲取從請求 object 注冊的所有路由,這是僅注冊一個 object 路由的示例(這些路由對象位於req.app._router.stack
中的數組內部):
Layer {
handle: [Function: router] {
params: {},
_params: [],
caseSensitive: undefined,
mergeParams: undefined,
strict: undefined,
stack: [Array],
_get: [Function],
_post: [Function],
_put: [Function],
_delete: [Function],
get: [Function],
post: [Function],
put: [Function],
delete: [Function],
setName: [Function],
lastRouteAdded: '/fromOthers',
names: [Array]
},
name: 'router',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/other\/path\/?(?=\/|$)/i { fast_star: false, fast_slash: false },
route: undefined
}
如您所見, path
未定義,但如果您看到,有一個名為:
regexp: /^\/other\/path\/?(?=\/|$)/i { fast_star: false, fast_slash: false }
這是一個包含路徑的正則表達式,所以如果我能得到那個正則表達式,我就能得到路徑,但似乎沒有辦法得到它,如果我嘗試這樣做(假設 var routeInstance
包含這個 JSON目的):
const path = routeInstance.regexp;
console.log(path);
我明白了:
/^\/other\/path\/?(?=\/|$)/i { fast_star: false, fast_slash: false }
但現在我不能得到那個正則表達式,如果我這樣做:
console.log(Object.keys(path));
我明白了:
[ 'fast_star', 'fast_slash' ]
如您所見,現在沒有正則表達式,如果我這樣做:
console.log(Object.keys(routeInstance));
(請記住,var routeInstance
包含 Layer 對象)我得到了這個:
[
'handle', 'name',
'params', 'path',
'keys', 'regexp',
'route'
]
那么,我怎樣才能得到那個正則表達式呢? 或者如果有其他方法可以得到它,我怎么能得到它?
筆記:
我知道app.use("/other/path", require('./routes'));
允許您放置一個正則表達式或數組而不是 static 路徑字符串,所以我的想法是route
助手根據過去的正則表達式返回最明顯的路由。
我很欣賞你的回復!!!
好的,我已經解決了,我可以讓那個正則表達式這樣做:
const regexpPath = routerInstance.regexp.toString();
似乎 JSON Object 被丟棄,只返回正則表達式字符串。
所以現在我可以用這個得到路徑:
// Search all ocurrences of type /some (Returns an array)
const pathOcurrences = regexpPath.match(/\/[A-Za-z0-9]+/igm);
// Remove the last element 'cause it will still bring me the / i of the regexp
pathOcurrences.pop();
// Join the ocurrences
const path = pathOcurrences.join("");
顯然,對於不是路徑的正則表達式,它會失敗,但這是正確的,你試圖從正則表達式中獲取路徑,你不能讓它工作^-^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.