user image

Mohamed Atef
Published in : 2021-06-13

[Solved] SyntaxError: Unexpected token o in JSON at position 1 NodeJS

Node JS & Mongo

SyntaxError: Unexpected token o in JSON at position 1 NodeJS, I am getting this error when I use JSON.parse function to decode the JSON from the request in NodeJS, 


SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at C:\nodejs\learning\test.js:6:28
    at Layer.handle [as handle_request] (C:\nodejs\learning\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\nodejs\learning\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\nodejs\learning\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\nodejs\learning\node_modules\express\lib\router\layer.js:95:5)
    at C:\nodejs\learning\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\nodejs\learning\node_modules\express\lib\router\index.js:335:12)
    at next (C:\nodejs\learning\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\nodejs\learning\node_modules\express\lib\middleware\init.js:40:5)

the code is 

const express = require('express');
const app = express();

app.post('/test', (req, res) => {
    res.status(200);
    res.send('Done '+ JSON.parse(req).body.firstName + ' ' + JSON.parse(req).body.lastName);
});

app.listen(3000, () => {
    console.log('Check your brwoser test');
});

Please help 

UPDATE 

I figured it out after a lot of searching I found out that I shouldn't use JSON.parse to decode the JSON data with Express JS so the right way is 

adding this line in the code

app.use(express.json()) 

so the code should look like 

const express = require('express');
const app = express();

app.use(express.json()) // Add this line

app.post('/test', (req, res) => {
    res.status(200);
    res.send('Done '+ req.body.firstName + ' ' + req.body.lastName);
});

app.listen(3000, () => {
    console.log('Check your brwoser test');
});
web-brackets.com

Comments

Jo Micheal Date : 2021-06-16

Best answers

5

Best answers

5

Great Job!! 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Way to bypass a value if it is not existing in Async data fetch iterations
Publish date: 2022-03-06 | Comments: 2

Tag: Node JS & Mongo