在 Node JS 中呈现包含数据的视图 [无框架]



我有一个名为/watch的端点,它获取数据并应返回包含已填充数据的页面。这个程序不是表达只是一个http服务器

和模板 EJS 视图

<!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>

节点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 Start,并将其与节点提供的准系统HTTP服务器相结合,该节点提供了以下示例:

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>

最新更新