CORS error: Likely due to app throwing an uncaught error during tests.
The 4th user story is:
You can POST to /api/users/:_id/exercises with form data description , duration , and optionally date .
You have:
app.post('/api/users/:_id/exercises', (req,res) => {
const id = req.body[':_id']
There should be no :_id property from the request body, because the form data only contains what is mentioned in the user story. The id is in the request parameter. Are you managing to get anything from req.body[':_id']?
The expected date format is a Date String (hint: use the .toDateString method:
newExercise.date = new Date().toISOString().substring(0,10)
Why do you get the id property twice here (just caught my eye):
let id = req.params['_id']
console.log(id)
Person.findById(req.params._id,
A lot of this date logic is unnecessary, and there is a small typo:
if(req.params.from || req.params.to){
let fromDate = new Date(0)
let toDate = new Date()
if(req.params.from){
fromDate = new Date(req.params.from)
}
if(req.params.to){
toDate = new Date(req.params.to)
}
fromDate == fromDate.getTime()
toDate = toDate.getTime()
resObject.log = resObject.log.filter((exercise) => {
let exerDate= new Date(exercise.date).getTime().toDateString()
return exerDate >= fromDate && exerDate <= toDate
})
Date objects in JS can be compared in any format - there is no need to convert them to a time.
Thanks for the reply, when i checked the console after submitting the text most of the error is about CORS policy. and i tried to solve it by adding the necessary code but am still having the same problem.
I also notice that the id is null when FCC is testing code
app.post('/api/users/:_id/exercises', (req,res) => {
const id = req.body[':_id']
const {description, duration, date} = req.body
const dateObj = date === '' ? new Date() : new Date(date)
let newExercise = new Exercise({
description,
duration,
date:new Date(dateObj).toDateString()
})
//609fb3f4af5e2900d278696e
Person.findByIdAndUpdate(id,
{$push: {log: newExercise}},
{new: true},
(err, data)=> {
if(!err){
let resObject = {}
resObject['_id'] = data.id
resObject['username'] = data.username
resObject['date'] = new Date(dateObj).toDateString()
resObject['duration']= newExercise.duration
resObject['description'] = newExercise.description
res.json(resObject)
}else{
res.json("invalid userId")
}
}
)
})
type or paste code here