如何将解析的JSON值存储到Express中的变量中?

时间:2016-06-22 04:20:50

标签: javascript json express

我正在使用body-parser来解析POST消息中的传入JSON对象。我想将JSON中的特定值存储到稍后要发送到数据库的变量中。

这是一个片段:

var http = require('http');

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');

    // Required to process the HTTP body.
    // req.body has the Object while req.rawBody has the JSON string.

    app.use(bodyParser.json()); // for parsing application/json

    app.post('/', function(req, res){

        var tropo = new TropoWebAPI();

        parameters = req.body['session']['parameters'];

        callerID = req.body['session']['from']['id'];
        console.log(callerID);

        if(callerID = 1234567)
        {
            \\Intentionally kept out
        }

但是,它因此类型错误而失败:无法读取属性' id'未定义的

@malix这是JSON对象:

"session": {
    "id": "89c3b5d830dd8bb8b372f802aadbdfc9",
    "accountId": "1234567",
    "applicationId": "1234567",
    "timestamp": "2016-06-23T17:09:48.685Z",
    "userType": "HUMAN",
    "initialText": null,
    "callId": "7ab0b9306af2139a1a2e6cc8b7bd7af9",
    "to": {
        "id": "408XXXYYYY",
        "name": "408XXXYYYY",
        "channel": "VOICE",
        "network": "SIP"
    },
    "from": {
        "id": "408ZZZAAAA",
        "name": "408ZZZAAAA",
        "channel": "VOICE",
        "network": "SIP"
    },  
}

我正在尝试提取408ZZZAAAA

请协助。

1 个答案:

答案 0 :(得分:0)

我想出来了。原来第一条POST消息确实给了我所需的结果。仅显示错误,因为我的APP配置为从源客户端触发第二个POST。触发相同app.post()的第二个POST没有“from”对象。因此,错误出现在第二次尝试,但我在第一篇文章中得到了我需要的东西。