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)