Home > Net >  JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24
JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24

Time:07-11

Me and others are experiencing this error: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following this tutorial on JSON Web Tokens (LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s, around minute: 10:00)

The error appears during this POST request:

Content-Type: application/json

{
  "username": "Kyle",
}

You can find the full code up to that point here: https://github.com/emanuelefavero/json-web-tokens

There are 3 main files to watch for:

  • server.js
  • .env (I left the .env file in the github repository)
  • request.rest (I used this file to make POST request but you can use POSTMAN or other methods)

The error seems to be in server.js, specifically in the express-JWT method:

app.post('/login', (req, res) => {
    // Authenticate User
    // Create json web token
    const username = req.body.username
    const user = { name: username }

    const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
    console.log(accessToken)
    res.json({ accessToken: accessToken })
})

The GET request is working fine.

While I'm trying to fix this error I'll still respond to any questions and provide project details if needed. Thank you.

Full Error Message:

SyntaxError: Unexpected token } in JSON at position 24
    at JSON.parse (<anonymous>)
    at parse (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/types/json.js:89:19)
    at /Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/read.js:128:18
    at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
    at invokeCallback (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:231:16)
    at done (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:220:7)
    at IncomingMessage.onEnd (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:280:7)
    at IncomingMessage.emit (node:events:402:35)
    at endReadableNT (node:internal/streams/readable:1343:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

CodePudding user response:

Chris.

It appears the issue lies in the request you're making. You have a trailing comma in the JSON that you are sending in your request.

If you are new to using JSON & JavaScript, just try to remember that JavaScript objects !== JSON.

In JS Objects, you can have trailing commas. However, in JSON it will cause issues.

Hope this helps.

  • Related