Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js – how to use a raw request body using Express

so I was making a RESTful API and I wanted to be able to receive raw json data (so I can use my api for mobile too), then from there save the data into my database (mongoDB).

But you see, there is this problem which I can’t seem to fix and its that I’m not able to use the raw data as a json.

The code is simple

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const express = require('express')
const bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});


app.post('/post', function(req, res){
 res.send(parse.JSON(req.body));
//to convert it to json but this doesn't seem to work
})

PS. I’m using postman to send the request as raw format

>Solution :

const express = require('express')
const bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});


app.post('/post', function(req, res){
 res.send(JSON.parse(req.body));
})

inside the res.send you have to use JSON.parse() instead of parse.JSON() which will throw an error as it is not correct

if you want to read more about JSON.parse you can visit mdn docs

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading