1

I encounter an error on client side while sending a variable using res.Render().

I'd like to send an object with arrays in it:

NodeJs:

var countries_lat_lng = [];
        trip.countries.forEach(country => {
            var country_lat_lng = {'latlng': CountriesJSON.find(f => f.alpha2Code == country.code).latlng};
            countries_lat_lng.push(country_lat_lng);
        });
        console.log(countries_lat_lng); //value: [ { latlng: [ -27, 133 ] }, { latlng: [ -41, 174 ] } ]
        res.render('myView', {
            coutriesLatLng: {countries_lat_lng}
        });

Javascript:

        var countriesMarkers = <%= coutriesLatLng %>;

And I have this following error on chrome:

    var countriesMarkers = [object Object]; Uncaught SyntaxError: Unexpected identifier

When I console.log() my countries_lat_lng variable, everything seems to be ok but rendered In javascript I have an error. Many thanks for your help.

2 Answers2

1

<%= ... %> is for outputting HTML, so what it's doing is converting your object to a string and HTML encoding it for output. Since you're generating JavaScript, what you want to do instead is to output the JSON of your data in a non-escaped format directly into your JS code.

Assuming coutriesLatLng is an Array, change this:

var countriesMarkers = <%= coutriesLatLng %>;

...to:

var countriesMarkers = <%- JSON.stringify(coutriesLatLng) %>;

The JSON.stringify will convert your Array to JSON, which is interpretable as a JavaScript expression. The <%- is for outputting that JSON without HTML-escaping it, so " doesn't become &quot;, for example.

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

Try this

var countriesMarkers = JSON.stringify('<%- coutriesLatLng %>');

Also I can see a problem here

res.render('myView', {
      coutriesLatLng: {countries_lat_lng}
});

I think this should be

res.render('myView', {
      coutriesLatLng: countries_lat_lng
});
Shijil Narayanan
  • 1,011
  • 8
  • 21
  • I have the same error doing this :/ var countriesMarkers = JSON.parse([object Object]); Uncaught SyntaxError: Unexpected identifier – Stefano Martines May 27 '20 at 16:37
  • Still not working but the error is not the same ^^ var countriesMarkers = JSON.parse([{"latlng":[-27,133]},{"latlng":[-41,174]}]); Uncaught SyntaxError: Unexpected token '&' – Stefano Martines May 27 '20 at 16:48