Search code examples
javascriptnode.jsexpressdust.js

How to pass client values from browser side to node.js controller


I am building a simple nodejs app and using dust at the client side. I am trying to get the lat, lng from the users location and want to make API call using node js express framework. So I get the lat, lng at the client side from the geolocation api. Now I want to pass the lat, lng to the controller so that I can query an API to show the user content. Sorry if this is really basic. I am new to both nodejs and dust. What I tried so far? 1. I tried to submit the form using jquery 2. Setting some dom values etc

$(document).ready( function() {
           var options = {
             enableHighAccuracy: true,
             timeout: 5000,
             maximumAge: 0
           };
           function success(pos) {
             var crd = pos.coords;
             document.querySelector("[name='latitude']").value = crd.latitude;
             document.querySelector("[name='longitude']").value = crd.longitude;
             console.log('Latitude : ' + crd.latitude);
             console.log('Longitude: ' + crd.longitude);
           };
           function error(err) {
             console.warn('ERROR(' + err.code + '): ' + err.message);
           };
           navigator.geolocation.getCurrentPosition(success, error, options);
    });

Controller code:

module.exports = function (router) {
    router.get('/', function (req, res) {
      //How do I pass the lat, lng from the client to controller?
    });
}

Solution

  • Just make a ajax call to your route path on the client side and in your router callback get the sent data

    Client

    //Make the ajax request
    $.post("/postLatLng",{lat:latVariable,lng:lngVariable});
    

    Node

    //hanlde the post request to /postLatLng
    router.post('/postLatLng', function (req, res) {
        var lat = req.param("lat");
        var lng = req.param("lng");
        //...
    });
    

    Express api