我需要读取通过 POST 表单发送的 Node.js 服务器中的嵌套 JSON 数据。
为了进行测试,我使用 Postman 发送 POST 请求 127.0.0.1:8080/extractByCenter
,与 Header Content-Type = application/json
和正文为“原始”JSON (application/json)
具有以下数据:
{
"center": {
"lng":17.4152,
"lat":40.4479
},
"radius":20
}
我使用 Node 启动的主 .js 文件非常简单:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
//------------------------------------
//Configuration
//------------------------------------
var config = require('./config.js');
app.use(morgan('dev')); //remove dev at the end of development
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//------------------------------------
//Routes
//------------------------------------
app.use('/', require('./routes/maprouter.js'));
//------------------------------------
//Server Start
//------------------------------------
mongoose.connect(config.DATABASE);
app.listen(config.SERVICE_PORT);
console.log('server start at port ' + config.SERVICE_PORT);
哪里maprouter.js
只需使用 MapManager.js 的一个函数即可:
var express = require('express');
var router = express.Router();
var MapManager = require("../managers/MapManager");
router.route('/extractByCenter').
post(function(req,res){
MapManager.extractByCenter(req.center,req.radius,function(err,data){
res.json({
success: true,
message: 200,
data: data
});
});
});
该函数仅获取 JSON 数据 center
和radius
并在数据库上执行查询。
var _ = require('lodash');
var config = require('../config.js');
var GeoJSON = require('../models/GeoJSON.js');
var Manager = {
extractByCenter: function(center,radius,callback){
var query = {
'coordinates' : {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ center.lng , center.lat ]
},
$maxDistance: radius,
$minDistance: 0
}
}
};
GeoJSON.find(query,'-__v -_id',callback);
}
}
module["exports"] = Manager;
问题出在中心数据的读取[ center.lng , center.lat ]
:
我有一个“TypeError:无法读取未定义的属性'lng'”
为什么center.lng(当然还有center.lat)不起作用?
最佳答案
bodyParser 将内容放在 req.body 上,而不是 req 上。因此,将您的代码更改为 req.body.center
和 req.body.radius
就可以了。
关于json - NodeJs - 嵌套 JSON POST 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49515971/