What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion.

Below is a fragment of the code:

var http = require('http');

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

    // Necessary for parsing the HTTP body.
    // req.body holds the Object while req.rawBody contains 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)
        {
            //Action intentionally omitted
        }

Unfortunately, it throws a TypeError: Cannot read property 'id' of undefined

@malix This is the structure of the JSON object:

"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"
    },  
}

I am aiming to retrieve the value 408ZZZAAAA

Your assistance is highly appreciated.

Answer №1

After some investigation, I have managed to solve the issue. It seems that the initial POST message provides me with the necessary outcome. The error occurs because my application is set up to initiate a second POST request from the original client. This subsequent POST call, which also triggers the same app.post() function, does not contain the essential "from" object. As a result, the error emerges on the second attempt, but I am able to obtain the required data from the first post itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with retrieving data from a file in Angular service while using node-webkit. Unable to make it functional

I've been struggling for a while and gone through numerous solutions, but I can't seem to figure out why this code isn't functioning: I have a requirement to pass data between controllers, so I created a service, right? (The data is coming ...

Run a PHP script that creates a PDF file using jQuery AJAX

I am currently working with a form that looks like this: <form action="tcpdf/examples/example_0611.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="subm ...

"click on the delete button and then hit the addButton

I have created a website where users can save and delete work hours. I am facing an issue where I can save the hours at the beginning, but once I delete them, I cannot save anything anymore. Additionally, when I reload the page, the deleted data reappears. ...

Having trouble sending Props between components within a specific route as I keep receiving undefined values

Here is the code for the initial component where I am sending props: const DeveloperCard = ({dev}) => { return ( <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}> <Button variant="primary">Learn More</Butt ...

Issue with executing Mongoose's .save() method

I am facing an issue with a piece of code that is not functioning as expected. My goal is to save a user document after modifying it with an ObjectId by adding it to an array. However, the user.save() function does not seem to execute, as the document rema ...

GdxError: Unable to Load Asset

I'm currently following a tutorial on managing groups of assets, but I am using JSON instead of XML. Even though I believe the asset is loaded, it seems to not be working properly! It would be greatly appreciated if someone could provide a solution. ...

Express Js: Conditional statement can only evaluate to true or false

I am stuck! Currently, I'm diving into learning Express.js. Everything seems to be going smoothly until I encountered a problem while trying to use an if else statement. The code block is not executing as expected - all I get are TRUE or FALSE result ...

Tips on retrieving the URL of a background image using "$event.target" to display in an Ionic modal

How can I display the clicked image in a modal? Implementation: <a ng-click="openModal($event)" ng-style="{'background-image': 'url(assets/img/img-01.jpg)'}"><img src="assets/alpha-4x3.png"></a> <a ng-click="openM ...

Challenges with precision when using JsonSlurper

I have a file containing data and configuration parameters that require modification before being used as the body data for a POST REST call. To retrieve the configuration value, I am utilizing a JsonSlurper. JsonSlurper slurper = new JsonSlurper() def i ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Go through every item in the list and update each element of the array with the outcome, doing so concurrently

Currently, I am struggling with implementing array asynchronous iteration functionality. I am working with the node-opcua library in Node.js. Specifically, I am using the function session.browse(nodeId, result). NodesTree = { "NodesTree":{ ...

Creating a new window using JavaScript with custom settings

Is it possible to create a window that opens when double clicking an icon on the desktop? I want this window to have specific dimensions and no menu bar or scrollbar. This is what my current code looks like: document.onload(openWin()); function openWin( ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Personalized search feature for Bootstrap tables

Below is the table structure: <table> <tr> <th>Number</th> <th>Name</th> </tr> <tr> <td>200.10.1234</td> <td>Maria Anders</td> </tr> <tr> < ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

Are you familiar with manipulating the JSON data array retrieved from an Ajax response?

Is it possible to handle a response from AJAX request in PHP? I'm not very familiar with JavaScript, so I'm struggling with this one. This is what I have managed to put together: var base_url = 'http://dev.local/westview/public'; $(& ...

Failure to Trigger AJAX Success Event

I am facing an issue while trying to retrieve a JSON string using an ajax call with JQuery. Despite getting a code 200 and success from the complete method, the success method itself is not triggering. function initialize() { $.ajax( { type ...

Tips for changing an input value when clicked using JQuery

Struggling to create an interactive mind mapping tool using JQuery? One challenge I'm facing is editing the content of a div once it's been set. I've implemented a function that successfully adds text to a div within the (mind-container). H ...

What is the best tool for syntax highlighting with Vue.js?

Looking for guidance on syntax highlighting with Vue.js. I've included the code snippet below, but for some reason the message "This is a test" isn't appearing as expected. Can someone please point out what mistake I may be making? <html> ...