Node JS body-parser get rawBody and body - node.js

I'm currently implementing the body parser in a way that is mentioned below
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));
Previously, it was just app.use(bodyParser.urlencoded({ extended: true})) and I got my data in req.body.
But due to some new requirements I had to use rawBody. Is there any way where I can get data in their respective formats in both rawBody and body
Right now, only either of rawBody or body works. Both don not work together.

While a tad hacky, I liked your idea of using the verify function to store the raw body somewhere. I believe your problem was caused by calling bodyParser.* too many times. It appears that only the last call does anything.
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
function rawBodySaver (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8')
}
}
app.use(bodyParser.urlencoded({
extended: true,
verify: rawBodySaver
}))
app.post('/', function (req, res, next) {
console.log(`rawBody: ${req.rawBody}`)
console.log(`parsed Body: ${JSON.stringify(req.body)}`)
res.sendStatus(200)
})
// This is just to test the above code.
const request = require('supertest')
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, () => {})
This prints:
rawBody: user=tobi
parsed Body: {"user":"tobi"}

Related

Getting binary body from request NodeJS

I need to write a handler for all types of form. I check the work via postman. What I've just written works for all forms except binary.
As a result, I get the error
PayloadTooLargeError: request entity too large
at readStream (/home/iskrayuriicr/projects/implement-echo-server/node_modules/raw-body/index.js:155:17)
at getRawBody (/home/iskrayuriicr/projects/implement-echo-server/node_modules/raw-body/index.js:108:12)
at read (/home/iskrayuriicr/projects/implement-echo-server/node_modules/body-parser/lib/read.js:77:3)
at rawParser (/home/iskrayuriicr/projects/implement-echo-server/node_modules/body-parser/lib/types/raw.js:81:5)
at Layer.handle [as handle_request] (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/layer.js:95:5)
at next (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/route.js:137:13)
at next (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/route.js:131:14)
at next (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/route.js:131:14)
at next (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/route.js:131:14)
at next (/home/iskrayuriicr/projects/implement-echo-server/node_modules/express/lib/router/route.js:131:14)
My code:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' })
const { raw } = express;
const port = 3000;
app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.text({limit: '50mb', extended: true}));
app.use(bodyParser.raw({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({parameterLimit: 100000, limit: '50mb', extended: true}));
app.all('*',raw({type: '*/*'}), upload.array('files', 12), (req, res) => {
console.log(req);
res.json({
method: req.method,
path: req.originalUrl,
query: req.query,
headers: JSON.stringify(req.headers),
body: {
fields: req.body,
files: req.files
},
});
});
app.listen(port,(err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
});
how to properly get body from such binary form?

request body is empty in post method node js server

Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})

NodeJS and body-parser

I tried to make a golden book width nodeJS. So I use body-parser to get my form's values and it works until I try to verify if my form is empty by this way :
app.post('/', (request, response) => {
if(request.body.message === undefined) {
console.log('Message : ' + request.body.message);
}
When I try to run my server and test my form by pushing informations, the loading of the page is infinite.
Can you help me please ?
Here, the full code :
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
// moteur de template
app.set('view engine','ejs');
// MIDDLEWARE
app.use('/assets', express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// ROUTE
app.get('/', (request, response) =>{
response.render('pages/index');
});
app.post('/', (request, response) => {
if(request.body.message === undefined) {
console.log('Message : ' + request.body.message);
}
});
app.listen(8080);
Your request is infinite, because you never finish it.
You can do it by simple
response.end()
in your request handler or if you want to return something to a client, then you can use
response.send({message: 'hello there'})

Express - `req.body` is always empty

I am trying to build a full stack(MERN) application. When I'm sending a request to my Express server with a JSON, I always see my req.body is empty. I can nowhere see my JSON inside my request.
I have tried using only app.use(bodyParser.json()) and app.use(bodyParser.urlencoded({ extended: true }));,but no change.
index.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
console.log("App");
require("./schema/data");
require("./routes/home_routes")(app);
require("./routes/table_routes")(app);
require("./routes/utility_routes")(app);
utility_routes.js
const mongoose = require("mongoose");
const Data = mongoose.model("data");
module.exports = app => {
app.get("/api/search_member", (req, res) => {
console.log("Utility", req);
console.log("Req Done");
// const search = await Data.findById({ member_id: req.body.member_id });
// console.log(search);
});
};
request.body
[0] body: {},
[0] route:
[0] Route {
[0] path: '/api/search_member',
[0] stack: [ [Layer] ],
[0] methods: { get: true } } }
request from client
onSearch = async value => {
console.log(value);
if (value) {
const searchData = await axios.get("/api/search_member", { value });
console.log(searchData);
}
};
You are making a GET request. GET request do not send body. To get req.body, make POST request to server.
Firstly:-
const searchData = await axios.post("/api/search_member", { value });
And Secondly,
app.POST("/api/search_member", async (req, res) => {
console.log("Utility", req);
console.log("Req Done");
});
This is what I use to accept the json
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json());
app.use(cookieParser());
And in the request set headers like this.
Content-Type : application/json
Both the axios and http libraries from angular works with this settings for me.

Nodejs Post Request no data in console

Not able to get any data in the following post request , any suggestions ?
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlEncodedParser = bodyParser.urlencoded({extended:false});
var app = express();
// add Service
app.post('/api/service/addService',urlEncodedParser, (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});
Will you try this
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
after that write your code -
app.post('/api/service/addService', (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});

Resources