2192

Passing array from NodeJS server to client?

Question:

Learning to make a webiste on my own. I had this issue before with a single object, but I was able to make it work and pick up the object on the client side and use it. But, now I'm trying to send an array of locations to the client in order to render them on the google maps api as markers (they have placeIDs stored in the JSON). According to the threads I've read once cannot send an array like an object, but I followed what some others suggested to no avail. I have some test locations I've made an array of, but when I try and pick it up on the client side I just get, "SyntaxError: missing : after property id" and "ReferenceError: cityList is not defined", which makes sense if the cityList is having issues.

Server:

var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { var yourCities = ["stockholm", "moscow", "barcelona", "bordeaux", "helsinki", "london"]; var cityList = yourCities.reduce(function(cityList, city) { cityList.push(require('../public/cityData/' + city)) return cityList; }, []) //TODO::need to update this to send an array res.render('map', { cityList : JSON.stringify(cityList), }); }); module.exports = router;

Trying to get the cityList clientside and make it into markers, the marker code is basically copied straight from Google's API guide.

<script> var cityList = <%- cityList %>; </script> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 41.9028, lng: 12.4964}, zoom: 3 }); var infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); for(i = 0; i < cityList.length; ++i) { service.getDetails({ placeId: cityList[i].placeID }, function(place, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address + '</div>'); infowindow.open(map, this); }); } }); } } </script>

Obviously, I'll later make marker placement into a loop but for now I'm just trying to get the first element for testing.

EDIT:: THE CODE IN HERE NOW IS WORKING FOR FUTURE USERS

Answer1:

It seems your way to sending data to ejs template is right and it should work fine, to be sure log the first item of cityList as bellow:

<pre class="snippet-code-js lang-js prettyprint-override">var cityList = <%= cityList %> console.log(cityList[0])

<strong>Update:</strong>

server

<pre class="snippet-code-js lang-js prettyprint-override">var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { var yourCities = ["stockholm", "moscow", "barcelona", "bordeaux", "helsinki", "london"]; var cityList = yourCities.reduce(function(cityList, city) { cityList.push(require('../public/cityData/' + city)) return cityList; }, []) //TODO::need to update this to send an array res.render('map', { cityList : JSON.stringify(cityList), }); }); module.exports = router;

Answer2:

JSON.stringify the array (or any arbitrary JSON object really) on the server and then JSON.parse it on the client.

So you need to change the client side code little bit.Please try below code it's working for me.

server-side:

res.render('map', { cityList : JSON.stringify(cityList), });

client-side:

var cityList = JSON.parse( !{JSON.stringify(cityList)} );

Recommend

  • How to Use 'IN' on a DataTable
  • Databinding in windows forms on an object graph with possible null properties?
  • Filter json data in node js
  • How to check the date format of the cell (oracle)
  • Excel - find nth largest value based on criteria
  • update dropdown values based on another dropdown - jQuery
  • Android: How to read the entire stacktrace from LogCat (including the ..X more errors)?
  • Find numpy.int_ in array of int_s using numba
  • How to run IntelliJ and Maven on OS X?
  • Set up React component to listen to socket.io
  • Is SQLite a good choice for a large, read only database for research?
  • deploy SQL Server Database with a Winforms app
  • How can I seekg() files over 4GB on Windows?
  • how to bind middleware to events in socket.io
  • Need to add username and password to SOAP header in VB.NET Web Service Client
  • Is it safe to uninstall VS Express after installing VS Ultimate?
  • Fold function in Octave
  • Conditional in Rails partial depending on the context page?
  • Microsoft.Web.Administration.ServerManager is connecting to the IIS Express instead of full IIS
  • Equivalent of every-pred, but for any of the given predicates
  • express.js can not get url's hash segment directly?
  • Using nodejs server with request package and function pipe()?
  • Cloud Functions for Firebase with custom HTTP path
  • download all file formats using angular and express JS
  • Global session variable in express.js route?
  • NodeJS - Disable JSONP on specific routes
  • Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?
  • parsing xml and html page with lxml and requests package in python
  • Can't connect Entity Framework to local SQL Server Express
  • Express JS Display Data By ID
  • Why is this giving me 2 different sets of timezones?
  • CORS with socket.io
  • How to resolve permission denied maybe missing internet permission?
  • Access variable of ScriptContext using Nashorn JavaScript Engine (Java 8)
  • How Lists (specifically, RecyclerView with CardViews) in Android work
  • Code in Job's Script Block after Start-Process Does not Execute
  • req.body is undefined - nodejs
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?