'Node - Pushing array from JS to Node

Here's my app.js file:

const express = require('express');

const app = express();
app.use(express.static(__dirname + '/assets'));

app.set('view engine', 'ejs');

app.listen(3000);

app.get('/', (req, res) => {
    const toSearch = []
    res.render('index', {toSearch});
})

app.use((req, res) => {
    res.status(404).render('404');
});

And here's a snippet of my JS file (on my index.js):

function addLatLng() {
  var name = document.getElementById('inputName').value();
  var lat = document.getElementById('latitude_input').value;
  var lng = document.getElementById('longitude_input').value;
  console.log('Name:'+name+'Latitude:' + lat + ', Longitude:' + lng);
}

I want to push the name, lat. lng data from my JS file into my app.js file. How do i achieve this? Im new to Node.js, and any help would be appreciated.



Solution 1:[1]

I think what you want here is a new express endpoint that can accept HTTP POST with a json body:

    const toSearch = []
    app.use(express.json());
    app.post('/update', (req, res) => {
        let json = req.body;
    
        toSearch.push({
            name: json['name'],
            lat: json['lat'],
            lng: json['lng'],
        })
        console.log(toSearch)
    
        return res.send('toSearch updated');
    })

On the clientside, you're going to need some sort of code to send the POST request:

      function addLatLng() {
        var name = document.getElementById('inputName').value;
        var lat = document.getElementById('latitude_input').value;
        var lng = document.getElementById('longitude_input').value;
        console.log('Name:' + name + 'Latitude:' + lat + ', Longitude:' + lng);

        var body = JSON.stringify({ name, lat, lng })
        fetch('/update', {
          method: 'POST',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
          },
          body: body
        }).then(res => console.log(res));
      }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew