简体   繁体   中英

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:

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:

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:

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 .

You probably want the route in checkout.js to be / .

Your checkout.js file should look like this, if you want have GET /checkout

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

router.get("/", (req, res) => {
    res.render("checkout");
});

module.exports = router

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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