[英]Node.js and express requiring routes from separate files only working for index routes
How to require/link routes from separate files?如何从单独的文件中要求/链接路由? I am using express router in the routes files then requiring the files in my app.js, but only the /home and /privacy-policy routes are working我在路由文件中使用快速路由器然后需要我的 app.js 中的文件,但只有 /home 和 /privacy-policy 路由工作
app.js:应用程序.js:
const express = require("express"),
app = express();
const indexRoutes = require("./routes/index");
checkoutRoutes = require("./routes/checkout");
app.use("/", indexRoutes);
app.use("/checkout", checkoutRoutes);
app.listen(PORT, () => console.log("Server Started"));
/routes/index.js: /routes/index.js:
const express = require("express"),
router = express.Router();
const checkoutRoutes = require("./checkout");
router.get("/", (req, res) => {
res.redirect("/home");
});
router.get("/home", (req, res) => {
res.render("index");
});
router.get("/privacy-policy", (req, res) => {
res.render("privacyPolicy")
});
module.exports = router;
/routes/checkout.js: /routes/checkout.js:
const express = require("express"),
router = express.Router();
router.get("/checkout", (req, res) => {
res.render("checkout");
});
module.exports = router
Your router handles /checkout
and you are mounting it at /checkout
which makes the full path to the route /checkout/checkout
.您的路由器处理/checkout
并且您将它安装在/checkout
,这构成了路由/checkout/checkout
的完整路径。
You probably want the route in checkout.js to be /
.您可能希望checkout.js 中的路由是/
。
Your checkout.js file should look like this, if you want have GET /checkout
如果你想要GET /checkout
,你的 checkout.js 文件应该是这样的
const express = require("express"),
router = express.Router();
router.get("/", (req, res) => {
res.render("checkout");
});
module.exports = router
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.