Mohamed Atef
13 Jun 2021
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');
});
Jo Micheal
16 Jun 2021
Great Job!!
© 2024 Copyrights reserved for web-brackets.com