How to resolve sequelize-JSON.parse error in Node


When I start with Sequelize ORM end up with the body-parser error. Usually we define body parser using app.use(bodyparser.json()), which globally declare parser functionality for all routes.

SyntaxError: Unexpected token in JSON at position 0
at JSON.parse ()
at createStrictSyntaxError (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:158:10)
at parse (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:83:15)
at E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:224:16)
at done (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:388:22)
at endReadableNT (node:internal/streams/readable:1305:12)
at processTicksAndRejections (node:internal/process/task_queues:80:21)

Here is where sequelize findAll() like functionality collides and the above error log will be populated

Solution

We can apply route specific parser to fix this mess. Let’s see how

Before the fix

For simplicity I have omitted some of the lines in index.js (Node project file). Before the fix our routes look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
app.use(bodyParser.json())

app.post("/todo",  (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


After the fix

After the removal of the global json parser it will look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
 

app.post("/todo", bodyParser.json(), (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


we have added the parser function of the bodyParser to Post routes only and the problem solved

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.