NodeJs - 嵌套的JSON POST输入

时间:2018-03-27 14:44:37

标签: json node.js postman

我需要在使用POST表单发送的Node.js服务器中读取嵌套的JSON数据。

为了测试我在127.0.0.1:8080/extractByCenter使用Postman和POST请求Header Content-Type = application/json进行测试 和身体作为"原始" JSON (application/json)包含以下数据:

{
    "center": {
        "lng":17.4152,
        "lat":40.4479
        },
    "radius":20
}

我用节点启动的主要.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 )不起作用?

3 个答案:

答案 0 :(得分:3)

bodyParser将东西放在req.body上,而不是req。因此,将您的代码更改为$conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = 'INSERT INTO test_tb (firstname, lastname, email) VALUES ( ?, ?, ? )'; //use ->prepare in favour of ->query if ($stmt = $conn->prepare($sql)) { //bind your inputs $stmt->bind_param('sss',$_POST['fname'],$_POST['lname'],$_POST['email']); //execute the prepared query if($stmt->execute()){ echo "New record created successfully"; } //You had a random ';' here that I've commented out?? //; } else { echo "Error: " . $sql . "<br>" . $conn->error; echo "</br>Stmt error: ".$stmt->error(); } req.body.center,您应该很高兴。

答案 1 :(得分:1)

当您发布表达时,正文解析器会将请求正文放入正文对象中。你试图从req.center和req.radius而不是req.body.center,req.body.radius访问它。

req.body.center, req.body.radius

var express = require('express');
var router = express.Router();
var MapManager = require("../managers/MapManager");

router.route('/extractByCenter').
    post(function(req,res){
        MapManager.extractByCenter(req.body.center,req.body.radius,function(err,data){
        res.json({
            success: true,
            message: 200,
            data: data
        });
    });
});

Ninja编辑:

尝试执行req对象的console.log,以便可以看到它包含的所有不同内容。

答案 2 :(得分:0)

req.body

确保身体解析器必须在那里