我第一次制作 MERN 应用程序,但此 res.render() 无法正确渲染。
const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient
const connectionString = 'mongodb+srv://abd456:[email protected]/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(err))
})
app.listen(3000,()=>{
console.log('hola')
})
}) .catch(错误 => console.error(错误))
这是浏览器结果。
" ��<�!DOCTYPE html> <�html lang="en"> <�head> <�meta charset="UTF-8"> <�meta name="viewport" content="width=device-width, initial-scale=1.0"> <�title>文件<�/title> <�/head> <�body> <�h1>无论我走到哪里都有你的影子!<�/h1> <�form action="/quotes" method="post"> <�input type="text" placeholder="name" name="name"> <�input type="text" placeholder="quote" name="quote"> <�button type="submit">提交<�/button> <�/form> <�/body> <�/html> "
我希望它呈现index.ejs,但它在浏览器中给出了html代码。
请帮忙
您还需要包含
ejs-mate
来渲染 ejs 模板。在终端中键入 npm install ejs-mate
,然后通过键入 const ejsMate = require('ejs-mate');
将其包含在您的 app.js 文件中,然后您需要通过在 app.js 文件中键入 app.engine('ejs',ejsMate);
(在 app.set('view engine', 'ejs);
之前和那么它可能应该正确渲染 ejs 模板。