简体   繁体   English

是否可以从 express.js 中的路由器中提取前缀?

[英]Is it possible to extract prefix from router in express.js?

I was wondering if it is possible to extract prefix from Router in express.js.我想知道是否可以从 express.js 中的 Router 中提取前缀。

Here is my index.js file:这是我的 index.js 文件:

const express = require("express");
const router = express.Router();

const admin = require("./admin");
const home = require("./home");

router.use("/admin", admin);
router.use("/", home);

// Catch All Other Pages
router.get("*", (req, res) => {
  res.render("404", { title: "404 Not Found" });
});

module.exports = router;

Here is my admin routes file:这是我的管理员路由文件:

const express = require("express");
const router = express.Router();

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu" });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings" });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

In the index.js file I have set prefix to be '/admin';在 index.js 文件中,我将前缀设置为“/admin”;

Can I know extract this prefix in the admin.js file?我可以知道在 admin.js 文件中提取这个前缀吗? Like for example:例如:

const express = require("express");
const router = express.Router();

// Require prefix
const prefix = router.getPrexix()?

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu", prefix });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings", prefix });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

Would it be possible to do this?有可能做到这一点吗? I could reuse '/admin' in the pug templates.我可以在 pug 模板中重用“/admin”。

In Express, req.baseUrl is the URL that the router was mounted on which would be "/admin" in your case.在 Express 中, req.baseUrl是安装路由器的 URL,在您的情况下为"/admin"

And, you have req.path which is what the route matched.而且,您有req.path ,这是路由匹配的内容。

And, you have req.originalUrl is the original URL so you can always use this in combination with either of the above to see the whole picture.而且,您有req.originalUrl是原始 URL,因此您始终可以将其与上述任一方法结合使用以查看整个图片。

Here's a little example to illustrate:这里有一个小例子来说明:

const express = require('express');
const app = express();

const router = express.Router();

router.get("/new", (req, res) => {
    console.log("baseUrl", req.baseUrl);                // "/admin"
    console.log("path", req.path)                       // "/new"
    console.log("originalUrl", req.originalUrl);        // "/admin/new"
    res.send("new");
});

app.use("/admin", router);

app.listen(80);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM