Express下/admin/article/new路由模板无报错无法渲染求助
核心问题排查
- 模板路径书写错误
当前代码里写的是res.render('/admin/article/new', ...),路径开头多了斜杠。Express读取模板时默认从项目根目录的views文件夹找文件,如果路径开头带斜杠,会被识别为文件系统的绝对路径,根本找不到你放在views/admin/article/下的模板文件。如果项目没配统一的错误捕获逻辑,模板读取失败时不会主动抛错,只会静默挂起无响应,刚好匹配你遇到的“无报错但渲染失败”的现象。
正确写法是去掉开头斜杠:res.render('admin/article/new', { article: new Article() }) - 路由定义和访问路径不匹配
正常打开新建文章页面是浏览器发起GET请求访问/admin/article/new,但你当前的路由文件里只定义了POST类型的signup、signin接口,完全没有注册对应路径的GET路由,哪怕模板路径写对,直接访问这个地址也匹配不到处理逻辑。 - 流程逻辑错位
现在你把渲染新建文章模板的代码,写在了登录接口(/signin POST)的成功分支里。就算路径写对,也只有提交登录表单成功后才会渲染这个页面,和你想要的“访问/admin/article/new直接打开新建页”的流程完全不匹配。 - 缺少全局错误捕获
不管是模板读取失败、数据库查询报错,没有统一的错误处理中间件的话,大量异常都会被Express静默吞掉,根本看不到报错信息,导致问题没法定位。
可参考的修正代码
const express = require('express'); const router = express.Router() const Article = require('../models/article') const User = require('./../models/users'); // 假设这个路由文件是通过 app.use('/admin', router) 挂载到主服务的 // 下面这个路由实际对应的访问地址就是 /admin/article/new,是GET请求 router.get('/article/new', (req, res, next) => { // 可在此处补充登录校验,未登录则重定向到登录页 try { res.render('admin/article/new', { article: new Article() }) } catch(e) { next(e) } }) router.post('/signup', async(req, res, next) => { req.user = new User() next() }, saveing()); function saveing() { return async(req, res) => { let user = req.user user.username = req.body.username user.password = req.body.password try { user = await user.save() res.send("ok saves") } catch (e) { // 把异常传给错误处理中间件,不要自己吞掉 next(e) } } } router.post('/signin', async(req, res, next) => { try { const user = await User.findOne({ username: req.body.username, password: req.body.password }) if (user) { // 登录成功后直接重定向到新建文章页,不要直接渲染,避免刷新时重复提交表单 res.redirect('/admin/article/new') } else { res.send("用户名或密码错误") } } catch(e) { next(e) } }) // 统一错误处理中间件,把异常信息打印出来,避免静默吞错 router.use((err, req, res, next) => { console.error('运行异常:', err) res.status(500).send('服务器内部错误') }) module.exports = router;
内容的提问来源于stack exchange,提问作者user14236736
相关产品推荐
相关产品推荐

