I am encountering an issue with a POST method, even though I believe I have implemented it correctly.
Error:
Unexpected token f in JSON at position 1
at JSON.parse
This error seems to make sense in some way, as 'token f' aligns with the beginning of my data: field1: "##########"
Here is the post function for my API:
var putNewNums = (data) => {
fetch('/getnums', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
})
.then(res => res.send())
}
This function points to the following route:
app.use('/getnums', getRouter)
which leads to this controller:
router.post('/', mainController.postNums)
The code for the controller is as follows:
postNums: (req, res, next) => {
numSchem.create({
field1: req.body.field1
})
.then(data => res.status(200).json(data))
.catch(e => {
req.error = e
console.log(e)
next()
})
}
I am uncertain about where the error lies. I am passing a string just like my schema specifies:
const nums = mongoose.Schema ({
field1: String,
})
Any insights on what might be incorrect in my implementation?
EDIT:
After updating req.boy to req.body.field1 in the postNums function, I encountered the following error:
{ ValidationError: numSchema validation failed: field1: Cast to String failed for value "{ field1: '8773238968' }" at path "field1"
at ValidationError.inspect (/Users/reid/Desktop/DupeFinder/server/node_modules/mongoose/lib/error/validation.js:59:24)
//Additional error details omitted for brevity