gpt4 book ai didi

node.js - 使用express to html在nodejs中渲染

转载 作者:太空宇宙 更新时间:2023-11-03 23:13:57 25 4
gpt4 key购买 nike

我正在尝试将 Nodejs 中的值转换为 HTML。我看过很多答案,但没有一个有效。

这是我到目前为止所做的:

index.html

    <!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>

</head>
<body>

<div>
<a id="test" name="test"> <%=name%></a>


</div>
</body>
</html>

app.js

   const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
const PORT = process.env.PORT ||2000;


app.engine('html', require('ejs').renderFile);

app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname+'/index.html'))
})


app.get('/test', (req, res)=> {

var name = 454;

res.render( "/index.html", {name:name});

});

app.listen(2001)

我不明白我做错了什么。但它没有按预期工作。知道我该如何解决这个问题吗?提前致谢 !

最佳答案

首先,创建一个文件夹 views 并将您的 index.ejs 放在那里(尽管我不确定,扩展名必须是 .ejs)。

然后设置引擎:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

并将您的路由更改为:

app.get('/', (req,res) => {
res.render('index', { name: 'Test' });
});

编辑:我已经使用了 express application generator还检查了 Using template engines with Express .

编辑:根据扩展名.ejs:

One thing to note is that all files in which ejs syntax are used in must be saved with a .ejs extension [...]

取自 Using EJS as a Template Engine in your Express App ,不是来自官方文档。

关于node.js - 使用express to html在nodejs中渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com