Tips for incorporating a User ID object into an Ajax request

Currently, I am delving into the world of web development and tackling a client-server project that involves allowing users to authenticate themselves and store their blood pressure readings. While the authentication part is functioning properly, I am encountering difficulties when it comes to storing a blood pressure reading. Despite successfully verifying all features using curl, I am facing errors from the server whenever I attempt to create a blood pressure reading. The root of my issue seems to lie in my inability to include the User ID as an object in the Ajax call. Any assistance on this matter would be greatly appreciated.

Below, you will find the curl script that is currently working:

API="http://localhost:4741"
URL_PATH="/readings"

curl "${API}${URL_PATH}" \
  --include \
  --request POST \
  --header "Content-Type: application/json" \
  --header "Authorization: Bearer ${TOKEN}" \
  --data '{
    "reading": {
      "systolic": "'"${S}"'",
      "diastolic": "'"`${D}`"'',
      "pulse": "'"${P}"'"
    }
  }'

echo

Here is the schema delineating the structure for the blood pressure reading:

const mongoose = require('mongoose')

const readingSchema = new mongoose.Schema({
  systolic: {
    type: Number,
    required: true
  },
  diastolic: {
    type: Number,
    required: true
  },
  pulse: {
    type: Number,
    required: true
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
})

module.exports = mongoose.model('Reading', readingSchema)

The following code snippet represents the blood pressure reading route that has been set up within the server app:

// CREATE
// POST /readings
router.post('/readings', requireToken, (req, res, next) => {
  // set owner of new reading to be current user
  req.body.reading.owner = req.user.id

  Reading.create(req.body.reading)
    .then(reading => {
      res.status(201).json({ reading: reading.toObject() })
    })
    .catch(next)
})

Additionally, here is the Ajax call made to the API:

// Create a reading
const readingCreate = function (data) {
  let dataToSend = [{ user: store.user._id }, { data }]
    dataToSend = JSON.stringify({ dataToSend })
  return $.ajax({
    method: 'POST',
    url: config.apiUrl + '/readings',
    data: dataToSend,
    headers: {
      ContentType: 'application/json',
      Authorization: 'Bearer ' + store.user.token
     }
  })
}

The Chrome Dev tools provide insight into the communication between the frontend and backend:

Request URL: http://localhost:4741/readings Request Method: POST Status Code: 500 Internal Server Error Remote Address: [::1]:4741 Referrer Policy: strict-origin-when-cross-origin

This is what the server console reports:

20:47:52 GMT-0600 (Central Standard Time): TypeError: Cannot set property 'owner' of undefined at router.post (/Users/Ken/sei/projects/project2/bp_tracker/app/routes/reading_routes.js:62:26)

Answer №1

When you send an array with the user ID, make sure to assign the value of req.body.user to reading.owner rather than using req.user.id for some reason.

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

After the update to the page, the DOM retains the previous element

I'm currently developing a Chrome Extension (no prior knowledge needed for this inquiry...) and I have encountered an issue. Whenever I navigate to a page with a specific domain, a script is executed. This script simply retrieves the value of the attr ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

When running the `vue-cli-service test:unit` command, an error involving an "Unexpected token" message related to the usage of the spread operator

Within my code, I am utilizing the destructuring operator. However, during the module build phase, I encountered an "Unexpected token" error. Any suggestions on how to resolve this issue without completely rewriting my code to avoid using the destructuring ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element searc ...

Is there a way to insert a label directly following a dropdown menu within the same table cell?

My goal is to include drop-down lists in a web page, so I decided to create a table structure using JavaScript. Firstly, I used the document.createElement() method to generate a table, table body, rows, and cells. Then, I proceeded to create select element ...

Is it conceivable to exploit JSON responses with appropriate JavaScript string escaping to launch an XSS attack?

Exploiting JSON responses can occur when Array constructors are overridden or when hostile values are not properly JavaScript string-escaped. To combat this, Google has implemented a technique where all JSON responses are prefixed with a specific code sni ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

Experiencing difficulties with executing numerous NodeJs queries

Could someone assist with rendering multiple queries in a Nodejs view? The console shows Promise {pending} and I can't figure out what's causing the issue. I'd appreciate any help or guidance on how to fix this problem. router.get('/ ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Having trouble getting the .push() method in JavaScript to function correctly

I've encountered an issue while trying to develop a function that iterates through each item in an array and records the index of a specific item when found. In this particular function, whenever the item 'contraband' is detected during the ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Issue with importing React: 'Module not found: Unable to locate'

I've organized my React project with a folder system, as shown in the screenshot below: https://i.stack.imgur.com/Rl9Td.png Currently, I'm attempting to import from context.js, located in src/context.js, into index.js, found in src/components/K ...

Dissecting Distinct and Alphabetized Attributes in JSON/JavaScript

Below is a code snippet that retrieves and organizes a list of values from JSON data in alphanumeric order based on a specific key-value pair: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &a ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...