json - NodeJs - 嵌套 JSON POST 输入

标签 json node.js postman

我需要读取通过 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 数据 centerradius并在数据库上执行查询。

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.centerreq.body.radius 就可以了。

关于json - NodeJs - 嵌套 JSON POST 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49515971/

相关文章:

oauth-2.0 - Salesforce OAuth 身份验证不适用于用户名和密码

jquery - 解析多级JSON

json - 返回空列表而不是 null

javascript - 无法读取 JSON 文件

node.js - 使用 mocha 和 request 测试 mongodb 数据库

javascript - 如何在 POSTMAN 上获得与浏览器相同的响应行为?

javascript - 将 Json 日期字符串转换为 JavaScript 日期对象

javascript - npm install package.json 中指定的确切包版本

arrays - 查询 MongoDB 中的整个对象数组

javascript - 向 node.js 服务发送请求会导致超时