Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
How do i post to mongodb database ? I have tried this but it still thrwoing error
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'

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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()
        })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda