Post请求后页面重定向失败问题排查求助
解决Express Post请求后无法重定向及"Cannot find module 'html'"报错问题
我来帮你搞定这个问题!你的核心问题有两个:一是Express找不到HTML模板引擎导致报错,二是Post请求里用错了返回方式,没有正确触发重定向。
问题根源分析
- 模板引擎错误:你设置了
app.set('view engine', 'html'),但Express本身并没有内置HTML模板引擎,它默认支持EJS、Pug这类动态模板,所以调用res.render()时,它会去寻找名为html的模块,自然找不到就报错了。 - 重定向方式错误:Post请求完成后,你想要的是让浏览器跳转到原来的页面,这时候应该用
res.redirect()触发浏览器的重定向请求,而不是用res.render()或者res.sendFile()。
具体解决方案
步骤1:移除不必要的模板引擎设置
直接删掉这行代码,因为你用的都是静态HTML文件,不需要模板引擎渲染动态内容:
app.set('view engine', 'html');
步骤2:修正Post路由的返回逻辑
把两个Post路由里的response.render()替换成res.redirect(),指向对应的Get路由路径:
比如原来的:
response.render("\LUNProvisionning.html");
改成:
response.redirect('/LUNProvisionning');
同理,VMProvisionning的Post路由也改成:
response.redirect('/VMProvisionning');
步骤3:优化路径写法(可选但推荐)
你之前的路径写法有些不规范,用path.join拼接更可靠,它会自动处理不同系统的路径分隔符。比如Get路由里的:
res.sendFile(path.join(__dirname + '/public/views/index.html'));
可以改成:
res.sendFile(path.join(__dirname, 'public', 'views', 'index.html'));
修正后的完整Node.js代码
const express = require('express'); const bodyparser = require('body-parser'); const app = express(); const path = require('path'); const router = express.Router(); app.use(bodyparser.urlencoded({ extended: false })); app.use(express.static(__dirname + '/public')); app.set('views', __dirname + '/public/views'); app.use('/', router); router.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'views', 'index.html')); }); router.get('/VMProvisionning', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'views', 'VMProvisionning.html')); }); router.get('/LUNProvisionning', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'views', 'LUNProvisionning.html')); }); app.post("/VMProvisionning", function (request, response) { console.log(request.body.environnement); console.log(request.body.vCPU); console.log(request.body.RAM); console.log(request.body.tailledisque); response.redirect('/VMProvisionning'); }); app.post("/LUNProvisionning", function (request, response) { console.log(request.body.serveur); console.log(request.body.volumetrie); console.log(request.body.type); response.redirect('/LUNProvisionning'); }); app.listen(8080, function () { console.log('Running on Port 8080'); });
这样修改后,提交表单时Post请求处理完成后会触发浏览器重定向到对应页面,同时也解决了找不到html模块的报错问题。
内容的提问来源于stack exchange,提问作者lucky simon
相关产品推荐
相关产品推荐

