2017-03-04 76 views
1

这里是我的server.js,获取JSON数据到控制器

const express = require("express"); 
var app = express(); 
var cons = require('consolidate'); 
const bodyParser = require('body-parser'); 

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()); 
app.engine('html', cons.ejs); 
app.set('view engine', 'html'); 

app.get("/getAllData", function(req, res) { 
    GPSDataSchemaModel.find({}, function(err, result) { 
     if (err) throw err; 
     if (result) { 
      res.render("index.ejs", { 
       dbData: result 
      }); 
     } else { 
      res.send(JSON.stringify({ 
       error: 'Error' 
      }) 
     )} 
    }) 
}) 

app.get("/onmap", function(req, res) { 
    console.log("Query type: " + typeof(req.query)) 
    console.log("Body type: " + typeof(req.body)) 
    console.log("Parameters type: " + typeof(req.params)) 
    res.send(req.query) 
}) 

这里是我的index.ejs,

<table class="table table-striped table-bordered" id="myTable"> 
 
        <thead> 
 
         <tr>       
 
          <td>In Map</td> 
 
         </tr> 
 
        </thead> 
 
        <tbody> 
 
        
 
        <% for(var i=0; i < dbData.length; i++) { %>       
 
        <tr> 
 
        <td><a href="/onmap?<%= JSON.stringify(dbData[i]) %>" class="btn btn-info" role="button">Map</a></td> 
 
        </tr> 
 
        <% } %> 
 

 
        </tbody> 
 
       </table>

MongoDB中的数据格式如下所示,

{ 
"_id": { 
    "$oid": "58ad111590c50e1ca0c1f352" 
}, 
"deviceID": "group-6-GPS", 
"deviceTime": "04:41:37", 
"deviceDate": "2016/06/07", 
"receiveTime": "10:18:29", 
"receiveDate": "2017/02/22", 
"latitude": 17.08, 
"longitude": 15.07, 
"fix": 0, 
"satellites": 0, 
"altitude": null, 
"deviceSpeed": 0, 
"devicecourse": 0, 
"deviceVariation": null, 
"__v": 0 
} 

点击地图按钮后,我得到这样的数据,

{ 
{"_id":"58ad111590c50e1ca0c1f352","deviceID":"group-6-GPS","deviceTime":"04:41:37","deviceDate":"2016/06/07","receiveTime":"10:18:29","receiveDate":"2017/02/22","latitude":"17.08","longitude":"15.07","fix":0,"satellites":0,"altitude":null,"deviceSpeed":0,"devicecourse":0,"deviceVariation":null,"__v":0}: "" 
} 

上述两项请注意数据格式都不相同。

我需要从第二个数据访问纬度经度。我怎样才能做到这一点?或者,我可以做什么来获得第二个数据为JSON?

+0

代码@ p0k8_非常感谢。它确实有效。 – Tareq

回答

1

如果你只是想提供查询纬度和longitutude那么,下面是提供的网址为

http://localhost:3000/onmap?latitude=17.08&longitude=15.07

和解析的查询将{"latitude":"17.08","longitude":"15.07"}

<table class="table table-striped table-bordered" id="myTable"> 
<thead> 
    <tr>       
     <td>In Map</td> 
    </tr> 
</thead> 
    <tbody> 
     <% for(var i=0; i < dbData.length; i++) { %>       
     <tr> 
      <td><a href="/onmap?latitude=<%= dbData[i].latitude %>&longitude=<%= dbData[i].longitude %>" class="btn btn-info" role="button">Map</a></td> 
     </tr> 
     <% } %> 
    </tbody> 
</table>