Having trouble extracting information from JSON object array following an AJAX post?

My website transfers data through JSON objects using Angular's $http post.

If you'd like to see the console logs and responses, visit my website:

Initially, I used x-form-urlencoded encoding successfully and decided to switch to application/json as I plan to push the data to MongoDB in the future.

While simple objects work well with req.body.___, more complex JSON objects and arrays are not functioning properly. Additionally, I am encountering a gateway timeout (504) error in response, though emails are being sent without issues via Amazon SES.

Below is an example of my HTML email code. I have tried various modifications but all result in 'undefined'. Despite this, console.log confirms that the data is being transmitted correctly.

replyTo: req.body.user[0].email,

subject: 'Clean Path Contact from '+ req.body.user.fname + ' '+ req.body[0].user.phone, // REQUIRED.
text: req.body.user + '\n' + '\n'  + 'Customer Name address: ' + req.body.user.fname[0] + '\n' + 'Customer email address: ' + req.body.user[0].email + '\n' +'Customer Phone Number: ' + req.body.user[0].phone,
};

This is an example of how my typical objects are structured:

{ user: {[
{
  "fName":"",
  "lName":"",

},
        {
            "name": "roomsclean1",
            "price": 27,
            "title": "Room(s) to clean",

          }, {
            "name": "roomsprotect1 ",
            "price": 62,
          }
    ]}

Alternatively, I sometimes use an array of objects like [{username: jim, lname: thomas}], yet req.body[0].username returns undefined.

In contrast, simpler objects like {username: jim, lastname: thomas} work seamlessly, and the email successfully receives the data.

Answer №1

Your JSON format was incorrect, please use the following structure and attempt with user[0].fname = demo

{
    "user": [
        {
            "fName": "demo",
            "lName": "dmo"
        },
        {
            "name": "roomsclean1",
            "price": 27,
            "title": "Room(s) to clean"
        },
        {
            "name": "roomsprotect1 ",
            "price": 62
        }
    ]
}

Answer №2

{
"user": [
    {
        "firstName": "",
        "lastName": ""
    },
    {
        "username": "roomsclean1",
        "cost": 27,
        "description": "Room(s) to clean"
    },
    {
        "username": "roomsprotect1 ",
        "cost": 62
    }
]

}

Here is a sample JSON for you to reference. If you access the first element of the user array, you will see the data.

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

Using HTML to showcase various prompt messages based on the screen resolution

For the button click event, when clicked on desktop screens it will show a prompt message saying 'Hi'. On the other hand, when clicked on mobile screens, the prompt message displayed will be "Hello". ...

Updating Key-Value pairs in an ArrayList using Angular 4

After importing json data into an arrayList and storing it in local-storage, the structure looks like this: [ { "id": 1, "name": "Albany", "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g", "price": 1 ...

Highlight the navigation transition in the menu

Is there a more updated tutorial available for creating an underline effect that slides from one link to another when hovered over and remains at the clicked link? I have come across a tutorial on Underline transition in menu which seems to be based on th ...

Two approaches for one single object

I'm trying to figure out why this particular code works // ....................................................... var character = { name: 'Joni', type: 'blond', sayName: function() { return this.name; }, sayT ...

ExpressJS facing a ReactCors problem

UPDATE: An error keeps popping up when I try to connect to my server: POST http://localhost:3001/user/login 500 (Internal Server Error) I'm not sure why this error persists and where I might be going wrong: React: export default class Account ex ...

connect the validation of forms to different components

I am currently working on components to facilitate the user addition process. Below is an example of my form component: createForm(): void { this.courseAddForm = this.formBuilder.group({ name: ['', [ Validators.required, ...

The deletion of Webpack Clean- /public/js has been successfully completed

I am utilizing the clean-webpack-plugin to empty the contents of my public/js directory. https://www.npmjs.com/package/clean-webpack-plugin Despite trying various methods, I keep encountering the message /public/js has been removed plugins: [ new CleanW ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

Utilizing JavaScript to dynamically alter an image based on selected dropdown option

I am currently facing an issue with my code where the selected image is not changing when I choose an option from the dropdown list. There are a total of 5 images, but for some reason, they are not displaying correctly. Here is the snippet of my code; < ...

Creating a JavaScript function in Selenium IDE specifically for today's date

Just starting out with Selenium IDE and looking to build a set of regression scripts for our department. Trying to insert today's date plus 180 days into a field using a JavaScript function. If anyone can guide me on how to write this function, I wou ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Obtain data from objects within an object

I'm struggling to access this information using JavaScript. This object contains nested objects. Here is how I am retrieving the information: $questions = Question::select('questions.id AS question_id' , 'questions.date', &apo ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

What's the best approach: Injecting a dependency into the main module or a controller in AngularJS?

I'm feeling a bit lost. There seems to be a difference in how dependencies are injected in AngularJS. Take for example the main module: angular.module("app", ["ui.router", "ui.bootstrap", "toaster"]); On the other hand, some dependencies can be inje ...

Error in mandatory data required by the Screenleap API in JavaScript

I have a JSON encoded data stored in a variable called $json. Here is how it appears: I have referred to the documentation at "https://www.screenleap.com/api/presenter" ...

preventing the page from scrolling whenever I update my Angular view

Whenever I update a part of my model that is connected to my view, my page automatically scrolls. I suspect that the page scrolling is triggered by the view updates. How can I stop this from happening? For instance, here is an example involving a dropdown ...

How can I respond with an error HTTP status code in Express utilizing Node.js?

While working on the login page, I encountered an issue with sending credentials from Angular to Express through a GET request. My goal is to have Express send a response if the data is found in the database, which can be handled by Angular. However, if th ...

Generating a one-of-a-kind json structure using pandas

I am currently working with a dataset that looks like this Year type Median_Home_Value 786252 2010 analyzed 11973.000 786253 2011 analyzed 12500.000 786254 2012 analyzed 13325.000 786255 2013 analyzed 14204.000 ...

Issues occurred when attempting to access information with postgres and nodeJS

Below is the configuration I have set up in my files: const express = require('express') const app = express() const port = 8000 const expense_model = require('./expense_model') app.use(express.json()); app.us ...

`Carousel nested within tabbed interface`

I am currently facing an issue with my website's tabs and carousels. I have 4 tabs, each containing a carousel, but only the carousel in the first tab seems to be working properly. When I activate the second tab, all the carousel divs collapse. For r ...