Reputation: 1053
I have an end point called /watch
that get data and should return page with filled data. This app is not express just a http server
and the template 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>
Is there any equivalent in node js
res.render('index', {
arr: data,
});
This is a snippet from the server code
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
}
})
Upvotes: 0
Views: 214
Reputation: 26878
You just need to send the String that ejs.render()
creates. Consider the barebones example that EJS shows: EJS#Get Started and combine that with the barebones HTTP server that node provides an example for:
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");
});
The network response I get back is:
* 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>
Upvotes: 1