const data = { name, price, quantity, image, desc, sup_name, email }
fetch('https://gentle-plateau-90897.herokuapp.com/fruits', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body:(data)
})
.then(res => res.json())
.then(data => {
console.log(data)
window.alert('Item added')
e.target.reset()
})
I am trying to post a method to send data to my MongoDB database, but it throwing an error saying ‘Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0’
2
Answers
Unexpected token < in JSON at position 0
means you are getting a HTML response instead of json response and you are trying to convert it to json. Check the response body in network tab in the dev tool. It might return HTML because you didn’t includeAccept: application/json
as header or some error happened.The error is coming due to the conversion of the
res
you are getting from the API. Theres
is something that can’t be converted to valid JSON.From the error, it seems that the
res
might be an HTML string and converting it to JSON will always yield an error. To use it, you should useinnerHTML
in the view.