Alejandro Decchi Alejandro Decchi - 2 months ago 8
Node.js Question

Post an Array in Javascript to Node.js

First thank you for trying to help me.
I want to know how pass(post,get) an Array in JS to Node.js backend to parse it then.
This is my Array:

var Coordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];


In the real stage, this Array is created when the user click the Google map. But this Array is an example what i need to send to my Node.js backend.
Thank you

Answer

You can do JSON.stringify(). This will convert your array into a string, which can be passed across the network via GET or POST. In the node server, you can parse this string and get the array using JSON.parse. Adding a working Example below

var Coordinates = [
      {lat: 37.772, lng: -122.214},
      {lat: 21.291, lng: -157.821},
      {lat: -18.142, lng: 178.431},
      {lat: -27.467, lng: 153.027}
                              ];

var a = JSON.stringify(Coordinates)
console.log('Coordinates string: ', a)

var parsed = JSON.parse(a)
console.log('Parsed Coordinates: ', parsed)

Comments