Mike
Mike

Reputation: 355

How to res.send() array with forEach()

Trying to get every item of an array sent to the client. But, for some reason it does not print into the browser

It works for console log, but not for res.send()

Is this possible without a template engine?

const express = require('express');
const app = express();

let theArray = [
  {id: '123441234',
  name: 'Joe',
  age: 21
},
{id: '458834',
name: 'Steve',
age: 28
}
]

app.get("/", (req,res) => {

  res.send(
    theArray.forEach(product => {
      `<h1>${product.name}</h1><br>
      <h5>${product.age}</h5>
      `
    });
  )
})

app.listen(3000)

Upvotes: 2

Views: 10529

Answers (2)

Marcos Luis Delgado
Marcos Luis Delgado

Reputation: 1439

You need to map the array instead of using a forEach loop. That way you can join the values and send the html string:

app.get("/", (req,res) => {

  res.send(
    theArray.map(product =>
      `<h1>${product.name}</h1><br>
      <h5>${product.age}</h5>
      `
    ).join('');
  )
})

This would result in your request getting the html:

<h1>Joe</h1><br>
<h5>21</h5>
<h1>Steve</h1><br>
<h5>28</h5>

Upvotes: 3

Julien TASSIN
Julien TASSIN

Reputation: 5212

res.send param must be a string and here it is an undefined object (forEach).

This should work :

const express = require('express');
const app = express();

let theArray = [
  {id: '123441234',
  name: 'Joe',
  age: 21
},
{id: '458834',
name: 'Steve',
age: 28
}
]

app.get("/", (req,res) => {

  res.send(
    theArray.map(product => {
      `<h1>${product.name}</h1><br>
      <h5>${product.age}</h5>
      `
    }).join(' ');
  )
})

app.listen(3000)

Upvotes: 1

Related Questions