skip to Main Content

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


  1. Use this way :

     <span>
          ${[1, 2, 3].map((el)=>el).join("")}
       </span>
    
    Login or Signup to reply.
  2. In a template literal the value of ${foo} is replaced by the result of evaluating the expression foo.

    The return value of forEach is undefined 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.

    ${[1, 2, 3].join("")} 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search