0

I am new in nodeJs When I try to return variable data to the server it's returning to a variable as a string.

Here is my app.js code

var express = require('express');
var app = express();
var dataFile = require('./data/data');
app.set('port', process.env.PORT || 3000);


app.get('/', (req, res) =>{
    console.log(dataFile);
    var info= '';
    dataFile.friends.forEach(function(item){

        info +='<li><h2>${item.name}</h2><p>${item.summary}</p></li>';
    });
    console.log(info)
    res.send("<h1>MMS</h1>${info}");
});
var Server = app.listen(app.get('port'), function(){
    console.log('listen to port '+app.get('port'));
});

Here is my data.json code

{
  "friends": [{
    "title" : "Class Friend",
    "name": "Ajay Negi",
    "shortname" : "Ajay",
    "summary" : "Intro",
    "description": "<p>Ajay was born in D.Dun </p>"
  },{
    "title" : "Best Friend ",
    "name": "Manpreet",
    "shortname" : "Manpreet",
    "summary": "Intro",
    "description": "<p>Manpreet was born in D.dun</p>"
  },{
    "title" : "ME",
    "name": "Vijay",
    "shortname" : "V.J",
    "summary": "INTRO",
    "description": "<p>Vijay was born in D.dun</p>"

  }]
}

When I run my browser its showing

enter image description here

In place of data If I am using js method to make li without $ and retun only info var than its working as I expected...

Mannu saraswat
  • 1,061
  • 8
  • 15
  • yes, it is, I have checked with console it's working... – Mannu saraswat Jan 13 '20 at 14:13
  • `"

    MMS

    ${info}"` is a plain string, it's not a string literal that does interpolation if given `${info}`. You need to surround this in backticks `\`` instead of quotes.
    – VLAZ Jan 13 '20 at 14:14
  • You're passing back strings, not processing or parsing has happened to those strings. You're not concatinating them, and if you're trying to use interpolated strings, you have to use backticks ``` instead of single quotes `'` – Malcor Jan 13 '20 at 14:15
  • Useful reading: [How to interpolate variables in strings in JavaScript, without concatenation?](https://stackoverflow.com/questions/3304014/how-to-interpolate-variables-in-strings-in-javascript-without-concatenation/) – VLAZ Jan 13 '20 at 14:16
  • Yes... you are right I am passing this as a string.. Thanks @VLAZ – Mannu saraswat Jan 13 '20 at 14:22

1 Answers1

2

Change res.send("<h1>MMS</h1>${info}"); to

res.send(`<h1>MMS</h1>${info}`);

Read more about template strings here.

Always Learning
  • 5,510
  • 2
  • 17
  • 34
Sagi Rika
  • 2,839
  • 1
  • 12
  • 32