如何将客户端值从浏览器端传递到node.js控制器

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

本文关键字:node 控制器 js 浏览器 客户端      更新时间:2023-09-26

我正在构建一个简单的nodejs应用程序,并在客户端使用dust。我正试图从用户位置获得最新的lng,并希望进行API调用使用node js表达框架。我从geolocation api获得客户端的lat。现在我想把lat, lng传递给控制器,这样我就可以查询了显示用户内容的API。抱歉,如果这是很基本的。我对nodejs和dust都是新手。到目前为止我尝试了什么?1. 我尝试使用jquery提交表单2. 设置一些dom值等

$(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);
    });
控制器代码:

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

只需在客户端对路由路径进行ajax调用,并在路由器回调中获取发送的数据

客户

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

节点

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

表达api