Home > Enterprise >  How do i post to mongodb database ? I have tried this but it still thrwoing error
How do i post to mongodb database ? I have tried this but it still thrwoing error

Time:05-08

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'

CodePudding user response:

The error is coming due to the conversion of the res you are getting from the API. The res 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 use innerHTML in the view.

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()) // remove this line for now
        .then(data => {
            /**
            check here what type of data you are getting 
            is it valid JSON or not?
            */
            console.log(data) 
            window.alert('Item added')
            e.target.reset()
        })

CodePudding user response:

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 include Accept: application/json as header or some error happened.

  • Related