我正在尝试分隔路线,之前我将其包含到我的app.js中
/backend/app.js
const express = require("express");
const router = require("./routes");
const status = require("./routes/status");
const register = require("./routes/register");
const login = require("./routes/login");
app.use('/', router);
app.use('/status', status);
app.use('/login', login);
app.use('/register', register);
我意识到它是不理想的,因为稍后我将添加越来越多的路由,而app.js将被它们污染
我现在要做的只是将index.js导入到app.js中,基本上该索引具有所需的所有路由
/后端/路由/索引
const routes = require("express").Router();
const root = require("./root");
const status = require("./status");
const register = require("./account/register");
const login = require("./account/login");
routes.use("/", root);
routes.use("/login", login);
routes.use("/register", register);
routes.use("/status", status);
and now in the app.js i can just include the index
const routes = require("./routes");
app.use('/', routes);
但在尝试请求登录路由时无法正常工作,并收到404错误
im像这样导出它们
module.exports = routes;
答案 0 :(得分:2)
在您的app.js中
app.use('/', require('./backend/routes/index'))
然后,在您的路线/索引中
import express from 'express'
const router = express.Router()
// GET /
router.get('/', function (req, res) {
})
// GET /countries
router.get('/countries', (req, res, next) => {
})
// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {
})
// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))
module.exports = router
您的管理员/索引文件可以是 从“快递”进口快递
const router = express.Router()
// POST /admin/login
router.post('/login', (req, res, next) => {
})
module.exports = router
通过此操作,您将能够向/ admin / login执行POST请求。
希望这可以解决您的问题,如果它确实将我的答案标记为正确,如果没有告诉我出了什么问题,我会解决它:D