javascript - 在 Node JS 中使用数据渲染 View [无框架]

标签 javascript node.js ejs

我有一个名为 /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/

相关文章:

node.js - 在 Raspberry pi 4 上运行 mongodb 服务器

node.js - Firestore promise 在退回产品之前等待产品详细信息

mysql - NodeJs 和 MySQL ER_BAD_FIELD_ERROR

javascript - 滚动位置到达屏幕中的元素位置时如何显示和过渡?

javascript - 为什么 .assign 对象合并中的 setter/getter 定义不起作用?

mysql - 无法使用 INSERT 和检索 SQL 条目?

javascript - AngularJS 的 $routeProvider templateUrl 总是使用 Express 返回 404

mysql - 如何使用node.js将excel文件导入MySQL?

Javascript - 从数组中删除数组

javascript - 你能给模态窗口(使用 Twitter-Bootstrap)一个 z-index 吗?