nodejs body-parser not able to get data - node.js

var express = require('express'); // Express instance to access its
var path = require('path');
var mongoose = require("mongoose"); // mongodb ODM
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000); //
app.use(express.static(path.join(__dirname, 'node_modules')));
mongoose.connect(config.MONGO_DB_URI, function(error){
if (error) {
console.log("Oops! Connection Failed! " + error);
} else {
console.log("Ahoy! Connection Successful with Mongo!");
}
});
app.use('/api', function(req, res){
console.log("dasasasa");
console.log(req.body);
});
module.exports = app;
when I log req.body it is an empty object {}.
Also the version of body parser is:
npm body-parser -v
2.15.9
What can i be missing here?
Also I am trying it with postman.

The bodyParser object exposes various factories to create middlewares. All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.
Make sure you're using some thing like:
Client.js:
$.ajax({
type: "POST",
url: '/yourRoute',
data: data,
dataType: dataType,
success: function(data) {
//do something
}
});
and server.js
app.use('/yourRoute', function(req, res) {
console.log(req.body) // should be data from client
})

Related

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 bodyparser returning undefined for body variables

I'm trying to extract POST data using a NodeJS script (with Express). The body is received, but I cannot seem to extract the variable from it when posting to the page with Postman. The variable is undefined, although I have used the same code I found in different questions. I have correctly installed Nodejs, express and body-parser.
To clarify, I'm posting form-data with Postman with key 'username' and value 'test'.
Anyone knows what I'm doing wrong?
var https = require('https');
var fs = require('fs');
var app = require('express')();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var httpsOptions = {
key: fs.readFileSync('/home/privkey.pem'),
cert: fs.readFileSync('/home/cert.pem'),
};
var server = https.createServer(httpsOptions, app);
server.listen(3000);
app.get('/', function(req, res) { //On get
res.send(req.method);
});
app.post('/', function(req, res) { //On post
res.send( req.body.username );
});
I guess it has to do with the encoding:
JSON:
you have to set a header with Content-Type: application/json and
add the encoding in express before the route :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Otherwise you can just use the option x-www-form-urlencoded and set the inputs

Can't get POST data using NodeJS/ExpressJS and Postman

This is the code of my server :
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.post("/", function(req, res) {
res.send(req.body);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".
However I keep getting an empty object in the response. The req.body property is always empty.
Did I miss something?
Add the encoding of the request. Here is an example
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..
Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw
Edit for use of raw
Raw
{
"foo": "bar"
}
Headers
Content-Type: application/json
EDIT #2 Answering questions from chat:
why it can't work with form-data?
You sure can, just look at this answer How to handle FormData from express 4
What is the difference between using x-www-form-urlencoded and raw
differences in application/json and application/x-www-form-urlencoded
let express = require('express');
let app = express();
// For POST-Support
let bodyParser = require('body-parser');
let multer = require('multer');
let upload = multer();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/sayHello', upload.array(), (request, response) => {
let a = request.body.a;
let b = request.body.b;
let c = parseInt(a) + parseInt(b);
response.send('Result : '+c);
console.log('Result : '+c);
});
app.listen(3000);
Sample JSON and result of the JSON:
Set Content-typeL application/JSON:
I encountered this problem while using routers. Only GET was working, POST, PATCH and delete was reflecting "undefined" for req.body. After using the body-parser in the router files, I was able to get all the HTTP methods working...
Here is how I did it:
...
const bodyParser = require('body-parser')
...
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
...
...
// for post
router.post('/users', async (req, res) => {
const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser
user.save().then(() => {
res.status(201).send(user)
}).catch((error) => {
res.status(400).send(error)
})
})
For PATCH and DELETE as well, this trick suggested by user568109 worked.
On more point I want to add is if you created your project through Express.js generator
in your app.js it also generates bellow code
app.use(express.json());
if you put your body-parser above this code the req.body will return null or undefined
you should put it bellow the above code see bellow for correct placement
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
I experienced the same issue. I tried all that had been suggested here. I decided to console log the value of the request object. It's a huge object. Inside this object I saw this query object carrying my post data:
query: {
title: 'API',
content: 'API stands for Application Programming Interface.'
}
So it turns out that request.query, and not request.body, contains the values I send along with my post request from Postman.

Request body undefined in supertest

I am testing an express API with supertest. I am trying to pass in body parameters into the test, as can be seen in the code snippets below, but it appears that the body parameters don't get passed in correctly since I get an error message that the body parameters are undefined.
Running the test with command mocha --recursive returns the following error:
Cannot read property 'email' of undefined
Below is the code from file email-suite.js referencing supertest
'use strict';
var express = require("express");
var bodyParser = require('body-parser');
var mongoose = require("mongoose");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var supertest = require("supertest");
var chai = require("chai");
var should = chai.should();
var api = require("../server.js");
describe("Email Module", function() {
this.timeout(25000);
before(function(done){
mongoose.createConnection(/* connectionstring */);
mongoose.connection.on('open', function(err) {
if(err) console.log(err);
console.log('connected to server');
});
done();
});
it("Check Email Count", function(done) {
var body = { email: "email#email.com" };
supertest(api)
.post("/emailCount")
.set('Accept', 'application/json')
.send(body) // body is undefined
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if(err) return done(err);
res.body.count.should.equal(2);
done();
});
});
});
Below is the code from file email-api.js
'use strict';
var express = require("express");
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/emailCount', function(req, res) {
var email = req.body.email; // req.body is undefined
}
module.exports = router;
Below is the code from the file server.js
var express = require("express");
var app = express();
app.set("port", process.env.PORT || 3000);
var router = require("./user/email-api");
app.use('/', router);
app.listen(app.get("port"), function() {
console.log("App started on port " + app.get("port"));
});
module.exports = app;
Put body-parser always after express object and before every routes in main server file like this
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Router task start from here
Other wise always will get undefined since router call first and body parsed later.
Thank you abdulbarik for your answer. I want to add some extra information to aid clarity in case people are still getting undefined values for the request body object, and if (as in my case) your routers and tests are setup differently.
Here is the router that we shall test:
// router.js
const express = require("express");
const router = express.Router();
router.post("/", (req, res) => {
res.json({ success: true, data: req.body });
});
module.exports = router;
The following test code will result in the request body being undefined, and thus the test failing:
// router.test.js
const express = require("express");
const request = require("supertest");
const bodyParser = require("body-parser");
// set up the test app - this will fail
const app = express();
app.use("/routerPath", require("./router")); // this will cause the test to fail, as the router should be setup after the body-paser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// run the test
it("successful response", async () => {
const response = await request(app)
.post("/routerPath")
.send({
firstname: "John",
lastname: "Smith",
})
.set("Accept", "application/json");
expect(response.status).toEqual(200);
expect(response.body).toEqual({
success: true,
data: {
firstname: "John",
lastname: "Smith",
},
});
});
The reason why, as explained by abdulbarik, is that the body-parser code should always be before the router code, so that the parser runs before the router. To make the test pass, simply swap these lines around:
// set up the test app - this will work now
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/routerPath", require("./router")); // the router setup should happen after the body-parse setup
I hope that is a helpful clarification.

request body undefined in node express

In node express when I try to access the post value from the form it shows request body undefined error.
Here is my code,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
Please any one help me to find why the request body shows undefined.
Enable body-parser middleware first
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
If you're not using express for the web server and just plain http. Use the body module.

Resources