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

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

Leave a Reply