Express.js不使用模板引擎渲染纯HTML及/about路由跳转报错问题求助
Express.js不使用模板引擎渲染纯HTML及/about路由跳转报错问题求助
嘿,我来帮你梳理下问题所在,其实都是几个容易踩的小坑:
首先说后端的核心问题:你用了res.render('about.html'),但res.render是给模板引擎用的(比如EJS、Pug这些),你没配置任何模板引擎的情况下,Express根本不知道怎么解析.html文件,这肯定会报错。既然你想只用纯HTML,那应该用res.sendFile,而且必须传绝对路径,不然Express可能找不到你的文件。
然后看你根路由的res.sendFile('index.html')其实也有问题,虽然可能暂时能跑,但路径是相对的,换个环境大概率会出问题,必须补全绝对路径。
另外前端的fetch请求也有问题:你请求/about后想把响应转成JSON,但/about返回的是HTML页面,JSON解析肯定会失败,这也是潜在的报错点。如果你的需求是点击按钮跳转到about页面,根本不需要fetch,直接跳转就行;如果是要获取HTML内容再处理,那得用response.text()而不是response.json()。
下面是修正后的完整代码:
修正后的server.js
import express from "express"; import path from "path"; import { fileURLToPath } from "url" const app = express(); const port = 3000; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // 静态文件服务,指向public文件夹 app.use(express.static(path.join(__dirname, 'public'))); // 根路由,用绝对路径返回index.html app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); // /about路由,同样用绝对路径返回about.html app.get('/about', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'about.html')); console.log(`Request Granted`); }); app.listen(port, () => { console.log('App listening on port ', port) });
修正后的前端index.html脚本(如果是跳转需求)
<script> const btns = document.getElementById('suc'); const btnd = document.getElementById('dan'); btns.addEventListener('click', async ()=>{ // 如果是要跳转到about页面,直接用location.href就行,不用fetch window.location.href = 'http://localhost:3000/about'; }) </script>
如果是要获取about.html的内容而不是跳转(可选)
<script> const btns = document.getElementById('suc'); const btnd = document.getElementById('dan'); btns.addEventListener('click', async ()=>{ try { let response = await fetch('http://localhost:3000/about'); // 用text()解析HTML内容,而不是json() let htmlContent = await response.text(); console.log(htmlContent); // 这里可以把htmlContent插入到页面里,比如document.body.innerHTML = htmlContent; } catch (err) { console.error('请求出错:', err); } }) </script>
解释下关键改动:
- 用
path.join(__dirname, 'public', '文件名')生成绝对路径,避免不同环境下的路径问题 - 把
res.render换成res.sendFile,符合纯HTML的需求 - 前端根据实际需求调整:跳转用location.href,获取内容用text()解析
这样改完应该就能正常访问/about页面,也不会报错了。
备注:内容来源于stack exchange,提问作者Muhammad Talha
相关产品推荐
相关产品推荐

