Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/455.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在node.js web服务中包含另一个参数?_Javascript_Node.js_Mongodb - Fatal编程技术网

Javascript 如何在node.js web服务中包含另一个参数?

Javascript 如何在node.js web服务中包含另一个参数?,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,抱歉,如果这是一个乏味的问题,我只是刚刚开始了解JS/node.JS如何处理post/get消息 我正在编写一个web服务,根据用户的纬度/经度和距离从mongodb数据库查询数据。我在前端代码中编写了以下函数: // Take query parameters and incorporate into a JSON queryBody $scope.queryUsersFromLast24Hours = function(){ // Assemble Query Bo

抱歉,如果这是一个乏味的问题,我只是刚刚开始了解JS/node.JS如何处理post/get消息

我正在编写一个web服务,根据用户的纬度/经度和距离从mongodb数据库查询数据。我在前端代码中编写了以下函数:

// Take query parameters and incorporate into a JSON queryBody
    $scope.queryUsersFromLast24Hours = function(){

        // Assemble Query Body
        queryBody = {
            longitude: parseFloat($scope.formData.longitude),
            latitude: parseFloat($scope.formData.latitude),
            distance: parseFloat($scope.formData.distance)
        };


        // Post the queryBody to the /query POST route to retrieve the filtered results
        $http.post('/queryUsersFromLast24Hours', queryBody)

            // Store the filtered results in queryResults
            .success(function(queryResults){

                console.log(JSON.stringify(queryBody));

                // Pass the filtered results to the Google Map Service and refresh the map
                gservice.refresh(queryBody.latitude, queryBody.longitude, queryResults);

                // Count the number of records retrieved for the panel-footer
                $scope.queryCount = queryResults.length;
            })
            .error(function(queryResults){
                console.log('Error ' + queryResults);
            })
    };
它从我的备份代码中调用方法
/queryUsersFromlast24小时
,如下所示:

// Retrieves JSON records for all users who meet a certain set of query conditions
    app.post('/queryUsersFromLast24Hours/', function(req, res){

        // Grab all of the query parameters from the body.
        var lat             = req.body.latitude;
        var long            = req.body.longitude;
        var distance        = req.body.distance;
        var dateNow           = new Date(); //right now



        // Opens a generic Mongoose Query. Depending on the post body we will...
        var query = User.find({});

        // ...include filter by Max Distance (converting miles to meters)
        if(distance){

            // Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
            query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},

                // Converting meters to miles. Specifying spherical geometry (for globe)
                maxDistance: distance * 1609.34, spherical: true});
        }
            console.log(dateNow);
            dateNow.setHours(dateNow.getHours()-24); //24 hours from now
            console.log(dateNow);
            query = query.where('created_at').gte(dateNow); //gte - greater then equal


        // Execute Query and Return the Query Results
        query.exec(function(err, users){
            if(err)
                res.send(err);

            // If no errors, respond with a JSON of all users that meet the criteria
            res.json(users);
        });
    });
<button type="button" class="btn btn-danger" ng-click="queryUsersFromLast24Hours()">Show data from last hour</button>
但是现在,如果我想让它更通用,并且返回的数据不是过去24小时的数据,而是用户给出的最后xx小时的数据,我应该如何修改它

我想创建一个Web服务,它不仅可以获取lat/long/distance数据,还可以获取若干小时的POST消息,并返回包含正确数据的json。那么,我应该如何修改前端/后端代码以包含此更改

另外,现在我从gui调用它,如下所示:

// Retrieves JSON records for all users who meet a certain set of query conditions
    app.post('/queryUsersFromLast24Hours/', function(req, res){

        // Grab all of the query parameters from the body.
        var lat             = req.body.latitude;
        var long            = req.body.longitude;
        var distance        = req.body.distance;
        var dateNow           = new Date(); //right now



        // Opens a generic Mongoose Query. Depending on the post body we will...
        var query = User.find({});

        // ...include filter by Max Distance (converting miles to meters)
        if(distance){

            // Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
            query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},

                // Converting meters to miles. Specifying spherical geometry (for globe)
                maxDistance: distance * 1609.34, spherical: true});
        }
            console.log(dateNow);
            dateNow.setHours(dateNow.getHours()-24); //24 hours from now
            console.log(dateNow);
            query = query.where('created_at').gte(dateNow); //gte - greater then equal


        // Execute Query and Return the Query Results
        query.exec(function(err, users){
            if(err)
                res.send(err);

            // If no errors, respond with a JSON of all users that meet the criteria
            res.json(users);
        });
    });
<button type="button" class="btn btn-danger" ng-click="queryUsersFromLast24Hours()">Show data from last hour</button>
显示上一小时的数据
那么,我如何修改它来传递将包含在后端查询搜索中的特定小时数呢


非常感谢你的帮助

好吧,如果您总是要减去X小时数,首先我建议您更改Web服务的名称,例如:queryUsersFromLastNHours

假设您将通过单击按钮触发该请求,那么您可以使用如下调用

<button id='myButton' ng-click="queryUsersFromLast24Hours()">MyButton</button>
<input id="numberOfHours" ng-bind="hoursToSubtract" />
为了更好地理解,请阅读

最后,在nodeJs代码中,更改

dateNow.setHours(dateNow.getHours()-24);
为了


好吧,如果你总是要减去X小时,首先我建议你改变你的Web服务的名称,比如:queryUsersFromLastNHours

假设您将通过单击按钮触发该请求,那么您可以使用如下调用

<button id='myButton' ng-click="queryUsersFromLast24Hours()">MyButton</button>
<input id="numberOfHours" ng-bind="hoursToSubtract" />
为了更好地理解,请阅读

最后,在nodeJs代码中,更改

dateNow.setHours(dateNow.getHours()-24);
为了

快速回答:

前端:

// Take query parameters and incorporate into a JSON queryBody
$scope.queryUsers = function(){

    // Assemble Query Body
    queryBody = {
        longitude: parseFloat($scope.formData.longitude),
        latitude: parseFloat($scope.formData.latitude),
        distance: parseFloat($scope.formData.distance)
        hours : Number($scope.formData.hours)
    };


    // Post the queryBody to the /query POST route to retrieve the filtered results
    $http.post('/queryUsers', queryBody)

        // Store the filtered results in queryResults
        .success(function(queryResults){

            console.log(JSON.stringify(queryBody));

            // Pass the filtered results to the Google Map Service and refresh the map
            gservice.refresh(queryBody.latitude, queryBody.longitude, queryResults);

            // Count the number of records retrieved for the panel-footer
            $scope.queryCount = queryResults.length;
        })
        .error(function(queryResults){
            console.log('Error ' + queryResults);
        })
};
后端:

// Retrieves JSON records for all users who meet a certain set of query conditions
app.post('/queryUsers/', function(req, res){

    // Grab all of the query parameters from the body.
    var lat             = req.body.latitude;
    var long            = req.body.longitude;
    var distance        = req.body.distance;
    var hours           = req.body.hours
    var dateNow         = new Date(); //right now



    // Opens a generic Mongoose Query. Depending on the post body we will...
    var query = User.find({});

    // ...include filter by Max Distance (converting miles to meters)
    if(distance){

        // Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
        query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},

            // Converting meters to miles. Specifying spherical geometry (for globe)
            maxDistance: distance * 1609.34, spherical: true});
    }
        console.log(dateNow);
        dateNow.setHours(dateNow.getHours()- hours); // XX hours from now
        console.log(dateNow);
        query = query.where('created_at').gte(dateNow); //gte - greater then equal


    // Execute Query and Return the Query Results
    query.exec(function(err, users){
        if(err)
            res.send(err);

        // If no errors, respond with a JSON of all users that meet the criteria
        res.json(users);
    });
});
抱歉,如果我误解了您的问题,但我想给您一些提示,此查询看起来像GET而不是POST,您可以使用查询参数或路径参数。

快速回答:

前端:

// Take query parameters and incorporate into a JSON queryBody
$scope.queryUsers = function(){

    // Assemble Query Body
    queryBody = {
        longitude: parseFloat($scope.formData.longitude),
        latitude: parseFloat($scope.formData.latitude),
        distance: parseFloat($scope.formData.distance)
        hours : Number($scope.formData.hours)
    };


    // Post the queryBody to the /query POST route to retrieve the filtered results
    $http.post('/queryUsers', queryBody)

        // Store the filtered results in queryResults
        .success(function(queryResults){

            console.log(JSON.stringify(queryBody));

            // Pass the filtered results to the Google Map Service and refresh the map
            gservice.refresh(queryBody.latitude, queryBody.longitude, queryResults);

            // Count the number of records retrieved for the panel-footer
            $scope.queryCount = queryResults.length;
        })
        .error(function(queryResults){
            console.log('Error ' + queryResults);
        })
};
后端:

// Retrieves JSON records for all users who meet a certain set of query conditions
app.post('/queryUsers/', function(req, res){

    // Grab all of the query parameters from the body.
    var lat             = req.body.latitude;
    var long            = req.body.longitude;
    var distance        = req.body.distance;
    var hours           = req.body.hours
    var dateNow         = new Date(); //right now



    // Opens a generic Mongoose Query. Depending on the post body we will...
    var query = User.find({});

    // ...include filter by Max Distance (converting miles to meters)
    if(distance){

        // Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
        query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},

            // Converting meters to miles. Specifying spherical geometry (for globe)
            maxDistance: distance * 1609.34, spherical: true});
    }
        console.log(dateNow);
        dateNow.setHours(dateNow.getHours()- hours); // XX hours from now
        console.log(dateNow);
        query = query.where('created_at').gte(dateNow); //gte - greater then equal


    // Execute Query and Return the Query Results
    query.exec(function(err, users){
        if(err)
            res.send(err);

        // If no errors, respond with a JSON of all users that meet the criteria
        res.json(users);
    });
});
抱歉,如果我误解了您的问题,但我想给您一些提示,此查询看起来像GET而不是POST,您可以使用查询参数或路径参数。

前端:

$http.post('/recentUsers?numHours=24', queryBody)
后端:

 var numberOfHours;
 if (req.query.numHours) {
   try {
     numberOfHours = parseInt(req.query.numHours)
   } catch(e) {}
 }
 numberOfHours = numberOfHours || 24; // default to 24 hours.
 dateNow.setHours(dateNow.getHours() - numberOfHours)
前端:

$http.post('/recentUsers?numHours=24', queryBody)
后端:

 var numberOfHours;
 if (req.query.numHours) {
   try {
     numberOfHours = parseInt(req.query.numHours)
   } catch(e) {}
 }
 numberOfHours = numberOfHours || 24; // default to 24 hours.
 dateNow.setHours(dateNow.getHours() - numberOfHours)

谢谢,你能告诉我你为什么在这里写
5
hoursToSubtract:5
?另外,现在在我的gui中,我通过单击按钮调用它。
ng click=“queryUsersFromLast24Hours()”
-我可以在括号中传递一个参数吗?我给了您一个例子。5是一个任意数。此“5”表示要发送到服务器的号码。我将编辑这个示例,向您展示一个更好的示例您可以传递任意参数是的,但我想这不是您想要的。在任何情况下,您都可以这样做
ng click=“queryUsersFromLast24Hours(5)”
,当然您必须在函数中将其作为参数接收谢谢,您能告诉我为什么在此处编写
5
hoursToSubtract:5
?另外,现在在我的gui中,我通过单击按钮调用它。ng click=“queryUsersFromLast24Hours()”-我可以在括号中传递一个参数吗?我给了您一个例子。5是一个任意数。此“5”表示要发送到服务器的号码。我将编辑这个示例,向您展示一个更好的示例您可以传递任意参数是的,但我想这不是您想要的。在任何情况下,您都可以这样做
ng click=“queryUsersFromLast24Hours(5)”
,当然您必须在函数中将其作为参数接收谢谢!我在上面的评论中问了类似的问题,但也许你可以回答我:)现在在我的gui中,我通过按钮单击调用它
ng click=“queryUsersFromLast24Hours()”
-我可以在括号中传递一个参数吗?谢谢!我在上面的评论中问了类似的问题,但也许你可以回答我:)现在在我的gui中,我通过按钮单击调用它
ng click=“queryUsersFromLast24Hours()”
-我可以在括号中传递一个参数吗?