You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js电商项目Admin路由404问题排查求助

Admin路由404问题排查与Node.js通用调试方法

我是Node.js新手,正在使用Node.js与PUG模板引擎开发一个简易电商网站,采用MVC架构。目前Shop路由运行正常,但Admin路由点击后始终返回404未找到。以下是相关代码文件:

相关代码文件

app.js

const path=require("path")
const express = require("express");
const app=express();
const bodyParser=require("body-parser");
const adminRoutes=require("./routes/admin")
const shopRoutes=require("./routes/shop")
const error404Controlle=require("./controllers/404")

app.set("view engine","pug")
app.set("view ","views")

app.use(bodyParser.urlencoded({ extended: false }))

app.use("/admin",adminRoutes)
app.use(shopRoutes)

app.use(error404Controlle.error404)

app.listen(3000)

admin路由文件(./routes/admin.js)

const express = require("express")
const router=express.Router();
const adminController=require("../controllers/admin")

//admin/add-product=>GET
router.get('/add-product',adminController.getAddedProducts);

//admin/add-product=>POST
router.post('/add-product',adminController.getPostAddProduct)


router.post('/edit-product',)
router.post('/admin-products-list',)
router.post('/adminHome',adminController.adminHomePage)

module.exports=router;

admin控制器文件(./controllers/admin.js)

const Product=require("../model/product")


exports.getAddedProducts=(req,res,next)=>{
    res.render("admin/add-product", )
}

exports.getPostAddProduct=(req,res,next)=>{
    const product=new Product(req.body.Title,req.body.Price,req.body.Description)
    product.save();
      res.redirect('/');
  }

  exports.adminHomePage=(req,res,next)=>{
      res.render('admin/admin-page',);
  }

PUG页面代码(触发Admin路由的页面)

doctype html
html(lang="en")
  head
    meta(charset="UTF-8")
    meta(http-equiv="X-UA-Compatible", content="IE=edge")
    meta(name="viewport", content="width=device-width, initial-scale=1.0")
    title Products
    link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css")
    link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css")
    style.
      body {
          display: flex;
          flex-direction: column;
          min-height: 100vh;
      }

      main {
          flex-grow: 1;
      }

  body
    header
      nav.navbar.navbar-expand-lg.navbar-light.bg-light
        ul.navbar-nav
          li.nav-item
            a.nav-link(href="/") Shop
          li.nav-item
            a.nav-link(href="/products") Products
          li.nav-item
            a.nav-link(href="cart") Cart

    main.container.mt-4
      h1.display-4 My Products
      if prods.length === 0
        p No products to show
      else
        .row
          each product in prods
            .col-md-4
              .card.mb-4
                img.card-img-top(src=product.imageUrl, alt=product.title)
                .card-body
                  h5.card-title #{product.title}
                  p.card-text #{product.description}
                  p.card-text
                    span Price: $#{product.price}
                    a.btn.btn-primary.float-right(href="#") Add to Cart
                      i.fas.fa-cart-plus

    footer.text-center.text-white(style="background-color: #0a4275;")
      section
        div.container.p-4.pb-0
          section
            p.d-flex.justify-content-center.align-items-center
              span.me-3 Admin Access
              a.btn.btn-outline-light.btn-rounded(type="button", href="/adminHome") Authorize
        div.text-center.p-3(style="background-color: rgba(0, 0, 0, 0.2);")
          | © 2023 Copyright:
          a.text-white(href="https://www.google.com/") Horizam.com

  script(src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js")

问题定位

导致404的核心原因有两个:

  1. 路由路径与方法不匹配:页面跳转链接是/adminHome,但admin路由挂载在/admin前缀下,且adminHome路由定义为POST方法,而页面点击发起的是GET请求。
  2. app.js配置小错误:app.set("view ","views")多了一个空格,应为app.set("views","views"),虽不直接导致404,但会影响模板查找。

修复步骤:

  • 修改admin路由文件,将router.post('/adminHome',adminController.adminHomePage)改为router.get('/adminHome',adminController.adminHomePage)
  • 修改PUG页面中的链接:a.btn.btn-outline-light.btn-rounded(type="button", href="/admin/adminHome") Authorize
  • 修正app.js中的模板路径配置:app.set("views","views")

Node.js开发中的问题排查方法

1. 路由匹配验证

  • 打印请求详情:在app.js中添加中间件,确认实际请求的方法和路径是否符合预期:
    app.use((req, res, next) => {
      console.log(`请求方法: ${req.method}, 请求路径: ${req.path}`);
      next();
    });
    
  • 核对路由前缀:确认app.use(prefix, router)的前缀与页面链接路径是否拼接正确。
  • 检查请求方法:确保页面发起的请求方法(GET/POST)与路由定义的router.get()/router.post()一致。

2. 文件路径校验

  • 确认模板位置:检查app.set("views", ...)指向的目录是否正确,res.render中的模板文件是否存在于对应目录(如views/admin/admin-page.pug)。
  • 验证路由文件引入:确认require("./routes/admin")的相对路径正确,避免路由未注册。

3. 中间件顺序检查

  • 404中间件需放在所有路由之后,避免提前拦截正常请求。
  • 解析类中间件(如body-parser)要放在路由之前,确保请求参数能被正确解析。

4. 日志与调试

  • 在路由、控制器中添加console.log,确认代码是否执行到目标位置。
  • 使用Node.js内置调试工具node inspect app.js,或VS Code调试功能单步跟踪代码流程。

内容的提问来源于stack exchange,提问作者RIZWAN ALI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:30:13