express3 js req.body is undefined - node.js

I am using express2.js when using req.body I get undefined or empty {}:
exports.post = function (req: express3.Request, res: express3.Response) {
console.log(req.body);
});
I have the following configurations:
app.use(express.bodyParser());
app.use(app.router);
app.post('/getuser', routes.getuserprofile.post);
The request body is in XML and I checked the request header which was correct.

I missed the part where you had XML. I guess req.body doesn't parse by default.
If you are using Express 2.x then perhaps this solution by #DavidKrisch is adequate (copied below)
// This script requires Express 2.4.2
// It echoes the xml body in the request to the response
//
// Run this script like so:
// curl -v -X POST -H 'Content-Type: application/xml' -d '<hello>world</hello>' http://localhost:3000
var express = require('express'),
app = express.createServer();
express.bodyParser.parse['application/xml'] = function(data) {
return data;
};
app.configure(function() {
app.use(express.bodyParser());
});
app.post('/', function(req, res){
res.contentType('application/xml');
res.send(req.body, 200);
});
app.listen(3000);

I don't believe express.bodyParser() supports XML. It only supports url-encoded parameters and JSON.
From: http://expressjs.com/api.html#middleware
bodyParser()
Request body parsing middleware supporting JSON, urlencoded, and
multipart requests.

Related

Body-parser fails to/do not parse urlencoded parameters from GET request

I'm creating a web platform with a Nodejs server. I'm trying to retrieve urlencoded data sent from my front but can't manage to.
How I send the GET request :
xhr.open("GET", address + "?limit=1&offset=1",true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
xhr.addEventListener("readystatechange", processRequest, false);
On the server side :
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.get('/guid_list', urlencodedParser, function (req, res) {
console.log(req.body.limit);
console.log(req.body.offset);
var headerjwt = HeaderGetJWT(req);
...
}
I have no problem retrieving the jwt token I'm sending, but always get undefined for urlencoded parameters.
I was wondering if I should use multipart content type instead, since I'm sending both a token and urlencoded data ? And maybe "multer" module in that case, since body-Parser does not support that content type.
I would suggest accessing your parameters in Node.js as follows (since they are being passed as query parameters):
app.get('/guid_list', parser, function (req, res) {
console.log("req.query.limit:", req.query.limit);
console.log("req.query.offset:", req.query.offset);
});
or just log all parameters:
app.get('/guid_list', parser, function (req, res) {
console.log("req.query:", req.query);
});

Postman send strange response for raw JSON post (node js)

I'm trying to do a POST request using raw json.
In the Body tab I have "raw" selected with this body:
{
"name": "book"
}
On the Node js side I'm doing res.send(JSON.stringify(req.body))
router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}
And in POSTMAN response I receive:
{"{\n\"name\": \"book\"\n}":""}
When expected something like
{"name":"book"}
Have no idea - where could be a reason for it?
You'll need to use the Express JSON body parser, install using
npm install body-parser;
Then:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.
Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")
Here's a simple express app that will echo any JSON POST:
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
If you're on Express v4.16.0 onwards, try to add this line before app.listen():
app.use(express.json());
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?
Can you log the response type from the server to console to check whether its already json content or not?
try with hard coded json response and then with dynamic variable
res.json({"name":"book"});

cURL post multiple fields along with file - form fields not displaying

I'm trying to POST multiple form fields, mixed with a file field, to my Node App, ver 7.4.0, using Express 4.0, but the fields aren't coming through to the server in the req object.
curl -X POST -H 'content-type: multipart/form-data' -F 'userEmail=my#gmail.com' -F upload=#/Users/me/Desktop/test_docs/doc1.xlsx localhost:5000/api/payments
But when I log console.log('REQ', req.body);, I get { }, when I expected at least userEmail present in the req.body.
I'm using bodyParser middleware as recommended
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true,
}));
Why isn't the form field coming through? Yet, if I post as application/JSON, I can see the fields in req.body.
According to the documentation of body-parser:
This does not handle multipart bodies, due to their complex and
typically large nature. For multipart bodies, you may be interested in
the following modules: busboy, connect-busboy, multiparty,
connect-multiparty, formidable, multer.
For example if multer:
// /api/payments.js
var express = require('express');
var router = express.Router();
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
/* POST /api/payments */
router.post('/payments', upload.single('upload'), function(req, res, next) {
res.json( req.body )
});

How do I get the post request with express js?

I'm trying to get the post variables in a little service I wrote but cannot seem to get it out of the request variable in my app.post method. I believe it's some way that I'm processing the request. Are there additional steps I must take to process the request? I've also tried using express.bodyParser() but I got an error saying that this is deprecated. The following is my little node.js file:
var express = require('express');
var app = express();
app.use(express.json());
// posting method : curl -X POST http://localhost:8080/post-page -d name=ArrowKneeous
// to look at the req I found it better to start using:
// nohup node testPost.js > output.log &
app.post('/post-page',function(req,res){
var name= req.body.name;
//undefined
console.log('name is :' + name);
//object
console.log('req is: '+req);
//object
console.log('req.body is: ' +req.body);
//undefined
console.log('req.body.name is: '+req.body.name);
//undefined
console.log('req.params[0]: '+req.params[0]);
//undefined
console.log('req.query.name is: '+req.query.name);
//empty brackets
console.dir(req.body);
//huge
console.dir(req);
//got stuff is replied to the curl command
res.send('got stuff');
});
app.listen(8080);
You have
app.use(express.json());
to process a JSON post, but are POSTing standard URL encoded form data.
-d name=ArrowKneeous
You either need to post JSON
-d '{"name": "ArrowKneeous"}' -H "Content-Type: application/json"
or you need to tell express to also accept URL encoded POST data.
app.use(express.urlencoded());
Edit
This applies to Express 3.x. It should be almost the same with 4.x, but you will need to load the body-parser module instead:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// OR
app.use(bodyParser.urlencoded());

Accessing Post Parameters in NodeJS from an Angular $resource.save Call

I am using an AngularJS Resource to make an ajax post to a node js server running express. However I am unable to access the post payload parameters on the NodeJS side.
I have a service set up:
angular.module('app.services', ['ngResource'])
.factory('PostService', function($resource) {
return $resource('/postTest');
});
and in the controller I have:
function UserCtrl($scope, PostService) {
//query for the users
$scope.testPost = function() {
var stuff = {firstname: 'some', lastname:'person'};
PostService.save(stuff,function(data) {
console.log('called save on PostService');
});
};
}
I can see the payload inside of the http header:
{"firstname":"some","lastname":"person"}
however, when I get to the NodeJS route to process it, I am not sure how to access the parameters:
(output from node console): inside test stuff
req.params undefined
app.post('/postTest', function(req, res) {
console.log('inside test stuff');
console.log('req.params ' + req.param('stuff'));
})
I have created a fiddle at: http://jsfiddle.net/binarygiant/QNqRj/
Can anyone explain how to access the parameters passed by the post in my NodeJS route?
Thanks in advance
If "{"firstname":"some","lastname":"person"}" is in the body of the post in json?
You'd access it differently.
Using express.bodyParser(), req.body.firstname will get you the firstname
app.use(express.bodyParser());
Then
app.post('/postTest', function(req, res) {
console.log('inside test stuff');
console.log(req.body.firstname);
})
You need to set body parser in your App
for example in ExpressJs 4,
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Resources