我有一个名为 /watch
的端点,它获取数据并应返回包含填充数据的页面。这个应用程序不只是一个 http 服务器
和模板 ejs View
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div class="container">
<div>Data</p>
<ul>
<% arr.forEach(function(elem) { %>
<li><%= elem %></li>
<% }); %>
</ul>
</div>
</body>
</html>
Node.js 中有没有等效的东西
res.render('index', {
arr: data,
});
这是服务器代码的片段
const server = http.createServer((req,res)=>{
const parsedUrl = url.parse(req.url,true);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g,'')
if(trimmedPath == "watch"){
var data = await GetData();
// here where i need to stuck sending the ejs template with data
}
})
最佳答案
您只需发送 ejs.render()
创建的字符串。考虑 EJS 显示的准系统示例:EJS#Get Started并将其与 Node 提供的准系统 HTTP 服务器结合起来 an example对于:
const http = require("http");
const ejs = require("ejs");
const template = "<div><%= people.join(',');%></div>";
const people = ["bob", "sue", "steve"];
const server = http.createServer((req, res) => {
res.end(ejs.render(template, {people}));
});
server.listen(8081, () => {
console.log("Listening on 8081");
});
我得到的网络响应是:
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8081 (#0)
> GET / HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Mon, 27 Aug 2018 17:10:01 GMT
< Connection: keep-alive
< Content-Length: 24
<
* Connection #0 to host localhost left intact
<div>bob,sue,steve</div>
关于javascript - 在 Node JS 中使用数据渲染 View [无框架],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52043843/