Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

457
Vistas
how to get rid of "unexpected token 0 in JSON at position 0"? which time this error is actually shown? What's the major reason to show this error?

First of all, please don't criticize me. I am beginner and I started to learn the server and working on it. But almost all the time I regularly found this error. I search this question and want's to know properly about it. But now I am becoming more confused because I don't know the major reason of showing this error. So, Please help me. As a beginner, It is the only errors that frustrates me a lot.

In the command Line I found this error

SyntaxError: Unexpected token 1 in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (C:\Projects\book-stock-server\node_modules\body-parser\lib\types\json.js:160:10)
    at parse (C:\Projects\book-stock-server\node_modules\body-parser\lib\types\json.js:83:15)
    at C:\Projects\book-stock-server\node_modules\body-parser\lib\read.js:128:18
    at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
    at invokeCallback (C:\Projects\book-stock-server\node_modules\raw-body\index.js:231:16)
    at done (C:\Projects\book-stock-server\node_modules\raw-body\index.js:220:7)
    at IncomingMessage.onEnd (C:\Projects\book-stock-server\node_modules\raw-body\index.js:280:7)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)

In the Client Side, I basically want's to decrease quantity 1 by 1 by clicking (handleDelivered) button and sent the quantity as a request to the server to store the quantity in MongoDB database. But when I implement this functionality it doesn't work and shows that error in the command line.

    const handleDelivered = () => {
        const updatedQuantity = { quantity: quantity - 1 };
        const url = `http://localhost:5000/books/${id}`;
        (async () => {
            try {
                const res = await fetch(url, {
                    method: "PUT",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(updatedQuantity.quantity)
                })
                const data = await res.json();
                if (data.modifiedCount >= 1) {
                    setbookInfo({ ...bookInfo, quantity: updatedQuantity.quantity });
                }
            }
            catch (err) {
                console.error(err);
                toast.error("There was a server side error");
            }
        })();
    }

Here in the server side I did exactly to store the quantity in the database and send the response to the client

            const id = req.params.id;
            const updatedQuantity = req.body;
            const filter = { _id: ObjectId(id) };
            const option = { upsert: true };
            const updatedDoc = {
                $set: {
                    quantity: updatedQuantity.quantity
                }
            };
            const result = await bookCollection.updateOne(filter, updatedDoc, option);
            res.send(result);
        })
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is caused by body-parser.

On this line it says:

      if (first !== '{' && first !== '[') {

… but the JSON specification was changed, years ago, to allow the top level data type in a JSON text to be any kind of JSON data and not just an array or object.

You are sending a number as your top level JSON data type, which is allowed by the current JSON specification, but which causes body-parser, in its default configuration, to throw an error.


You can change body-parser to support the current spec with a configuration option:

strict

When set to true, will only accept arrays and objects; when false will accept anything JSON.parse accepts. Defaults to true.

Alternatively, a work-around would be to send an object instead of a number:

body: JSON.stringify(updatedQuantity)

You would need to change the server side code to read req.body.quantity instead of req.body

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda