首次开发MERN应用遇res.render()渲染异常求助
问题:Express使用res.render()渲染EJS模板时浏览器直接显示HTML代码
首次开发MERN应用,使用Express的res.render()方法尝试渲染index.ejs模板,但浏览器未正常渲染页面,而是直接显示HTML代码,且输出带有乱码。以下是相关代码及浏览器输出:
相关代码
const express = require('express') const bodyParser = require('body-parser') const MongoClient = require('mongodb').MongoClient const connectionString = 'mongodb+srv://abd456:abd123@cluster0.exnpi0k.mongodb.net/expresslearn?retryWrites=true&w=majority' const app = express() MongoClient.connect(connectionString, { useUnifiedTopology: true }) .then(client => { const db = client.db('star-wars-quotes') const quotesCollection = db.collection('quotes') app.set('view engine', "ejs") app.use(bodyParser.urlencoded({ extended: true })) app.get('/', (req, res) => { db.collection('quotes') .find() .toArray() .then(results => { console.log(results) res.render('index', { quotes: results }) }) .catch(error => console.log(error)) }); app.post('/quotes', (req, res) => { quotesCollection .insertOne(req.body) .then(result => { res.redirect('/') }) .catch(error => console.error(error)) }) app.listen(3000, () => { console.log('hola') }) }) .catch(error => console.error(error))
浏览器输出
" ��<�!DOCTYPE html> <�html lang="en"> <�head> <�meta charset="UTF-8"> <�meta name="viewport" content="width=device-width, initial-scale=1.0"> <�title>Document<�/title> <�/head> <�body> <�h1>wherever I go there's a shadow of you!<�/h1> <�form action="/quotes" method="post"> <�input type="text" placeholder="name" name="name"> <�input type="text" placeholder="quote" name="quote"> <�button type="submit">submit<�/button> <�/form> <�/body> <�/html> "
解决方法
- 确认EJS依赖已安装:运行
npm install ejs,确保项目已安装EJS模板引擎,否则Express无法编译EJS文件。 - 检查模板文件位置:Express默认从项目根目录的
views文件夹读取模板,确保index.ejs放在./views/index.ejs路径下;如果模板在其他目录,需通过app.set('views', './你的模板目录')指定路径。 - 修复响应编码问题:浏览器输出的乱码说明响应编码异常,可全局设置响应头确保编码为UTF-8:
app.use((req, res, next) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); next(); }); - 修正代码错误:原POST路由的catch回调里使用了未定义的
err变量,需改为error,避免未捕获的错误导致响应异常。
内容的提问来源于stack exchange,提问作者Abdhul Basith
相关产品推荐
相关产品推荐

