I want to write some html code in a nodejs application when the user requests. I want to show the array elements on the page as the following code:
const http = require('http');
const port=3000;
http.createServer((req, res)=>{
const {url , method , headers} = req;
res.write(`<html>
<head>
<title>My yest</title>
</head>
<body>
<h1>This is my h1</h1>
<p>
This is my first paragraph. The request method and url are: ${method} , ${url}
</p>
<p>
The items:
<span>
${[1, 2, 3].forEach((el)=>{
{el};
})}
</span>
</p>
</body>
</html>`);
res.end();
}).listen(3000);
But the following code does not work as I desire. I want the array elements to be shown in the second paragraph.Whats wrong and how may I do that? I don’t want to use view engine for it.
<span>
${[1, 2, 3].forEach((el)=>{
{el};
})}
</span>
2
Answers
Use this way :
In a template literal the value of
${foo}
is replaced by the result of evaluating the expressionfoo
.The return value of
forEach
isundefined
so${[1, 2, 3].forEach((el)=>{{el};})}
gives you nothing.(Aside from that,
(el)=>{{el};}
gives you nothing anyway).You probably want to use
join
instead.