I'm trying to use the fetch api for a post request to the database. I am making a simple discussion platform and am trying to allow for the user to submit a form that gets saved in mongo.
This is my route in my handlers.js file:
router.post('/add', async (req, res) => {
console.log('inside post method')
const userComment = { userid: "testUser" + stringify(Math.random()), commentid: "comment" + stringify(Math.random()), content: req.body, reply: false }
//const userComment = req.body
const newComment = new commentModel(userComment)
try {
await newComment.save(async (err, newCommentResult) => {
console.log('New comment created!')
res.end('New commentcreated!')
})
} catch (err) {
console.log(err)
res.end('Comment not added!')
}
})
This is my fetch in my front end:
function addComment (content) {
console.log(content)
//**** NOT DONE , NEW COMMENT ADD INTO DATABASE */
//!!!!! Call api request here !!!!//
const type = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(content),
mode: 'cors'
}
fetch('/add', type)
.then(
console.log('success')
)
.catch(
error => console.log('error', error)
)
}
I am basically trying to submit data via a form that gets saved in mongo.