req.body in nodejs is coming empty:{}? - angularjs

This is my angular http request which makes a delete request when deleteEmployee function is called:
This function is called on click of event:
$scope.deleteEmployee=function(index){
$http({
method:'DELETE',
url:'/delete',
data:{
"ndx":"abc"
}
}).then((response)=>{
console.log(response);
})
}
And this is my server.js file
var http=require('http');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/',express.static(__dirname));
app.delete('/delete',function(req,res){
console.log(req.body);
})
app.listen(8888,()=>{
console.log('Server Started');
})
On console.log(req.body) it show empty i.e. {}.

From https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5:
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
Basically, DELETE requests must not have a body.

Try changing syntax :
$http.delete('/delete',{"ndx":"abc"});

Related

req.body empty Node.js

this is my angular controller code where im passing certificationid and userid to delete certification details of a user.
$scope.deleteCertification = function(CertificationId){
var userName = $scope.userId;
var certificationId = CertificationId;
var deleteCertificationInfo = {'userName': userName, 'certificationId':certificationId};
console.log('deleteCertificationInfo*******');
console.log(deleteCertificationInfo);
userProfileService.deleteUserCertificationInfo(deleteCertificationInfo).then (function(data){
console.log($scope.Certification);
console.log('Certification Deleted');
})
}
userProfileData.deleteUserCertificationInfo = function (deleteCertificationInfo) {
var deferred = $q.defer();
$http.delete('/api/profileUpdate/deleteUserCertification', deleteCertificationInfo, {
}).success(function(res){
var deletedUserCertificationResult = res;
deferred.resolve(deletedUserCertificationResult);
$log.debug('response from certification API:['+JSON.stringify(deletedUserCertificationResult)+']');
}).error(function(err){
deferred.reject(err);
});
return deferred.promise;
};
that is written in userProfileService to call the delete API.
but in my node controller function req.body is empty. not sure where it is going. im consoling the data in front end before sending it to service . it's displayed then. but why the req.body is getting empty?
Even though you haven't posted the Express portion of your app, the best guess here is that you're not using body-parser. body-parser is an Express middleware that is required when using req.body, without adding it to your Express app, you won't be able to parse any incoming JSON or url-encoded request bodies.
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
let app = express();
app.use(bodyParser.json()); // this will parse Content-Type: application/json
app.use(bodyParser.urlencoded({ extended: true })); // this will parse Content-Type: application/x-www-form-urlencoded
// Your routes go here
app.listen(port);
try with the follwing code, its worked for me , you shoud have this code in your node service js file
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));

Handle sessions using Express-Sessions

Im new working with nodeJS. I have a webpage (with AngularJS) in a AWS ec2-server that gets information from a nodeJS(Express) server. Im trying to keep logged my users once they log in, even if they refresh. I have read that I can do that using express-sessions. This is my code in the client side:
$http({
method: 'GET',
url: 'http://ec2-bla-bla-bla.compute.amazonaws.com:8080/verifySession'
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
});
//And here i have the http post method that call login webservice
This is my server code:
var express = require('express');
var bodyParser = require('body-parser');
var path = require("path");
var session = require('express-session');
var app = express();
var loginManual = require('./model/ws_package/loginManual.js');
var sess;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(session({secret: 'ssshhhhh'}));
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.static(path.join(__dirname + '/view')));
app.get('/verify',function(req,res){
sess=req.session;
if(sess.email){
res.send({state:1,email: sess.email});
}
else{
res.send({state:-1,email: "NE"});
}
});
app.post("/login",function(req, res)
{
var userEmail; //here is myuseremail
//I have some login code here and if it is successful:
sess = req.session;
sess.email=userEmail;
res.send(response);
}
);
It is not working, but when I tested /login and /verify webservices, directly in my browser, writing the url, it works. Another thing I discovered is that everytime I make a new $http method from angular, my session id changes, so I dont know if that could mean something that affects me. How can I solve this? Sorry for my english, i am Costa Rican! Thanks!

Getting angularJS $http.post from nodeJS

Please help me, I would like to get angularJS $http.post parameter that being sent to be processed in nodeJS.
I would like to see whether the parameter (nama, nip, pernr, etc...) was sent successfully, but the result is undefined as shown below :
angularJS code :
// ADMINISTRATOR ========================================
.state('talentapegawai.uploadtalenta.douploadtalenta', {
views:{
"monitorupload": {
url: '/douploadtalenta',
templateUrl: '/progressupload.html',
controller:function($scope, $http, XLSXReaderService){
$scope.prograssing2 = true;
for(var i=0; i < $scope.sheets[$scope.selectedSheetName].length; i++){
$http.post("/execuploadtalenta",{'nama': $scope.sheets[$scope.selectedSheetName][i].nama, 'nip': $scope.sheets[$scope.selectedSheetName][i].nip, 'pernr':$scope.sheets[$scope.selectedSheetName][i].pernr, 'tgl_grade_terakhir': $scope.sheets[$scope.selectedSheetName][i].tgl_grade, 'singkatan_talenta': $scope.sheets[$scope.selectedSheetName][i].talenta_abbr, 'talenta': $scope.sheets[$scope.selectedSheetName][i].talenta, 'mulai':$scope.sheets[$scope.selectedSheetName][i].mulai, 'akhir':$scope.sheets[$scope.selectedSheetName][i].akhir})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
}
$scope.prograssing2 = false;
}
}
}
})
NodeJS code (express) :
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/execuploadtalenta', requireLogin, function (req, res) {
console.log("NILAI REQUEST : "+req.body.nama); -->return undefined
console.log("NILAI REQUEST : "+req); -->return [object, object]
});
server.listen(3333);
First of, Tell body-parser to parse json requests:
app.use(bodyParser.json({limit: '10mb'}));
Its also a good practice to limit the size of json objects
Then, You should be able to read the body as a JSON object.
Take a troubleshooting tip, just to make sure what you get in the body is correct, you can print it as string:
console.log(JSON.stringify(req.body));

In Express.js with body-parser the value of request.body is undefined

I'm having a problem I cannot diagnose.
On a server, I have a simple URL handler using Express.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
app.configure(function() {
app.use(app.router);
app.use(bodyParser.json()); // see: http://expressjs.com/api.html#req.body
app.use(bodyParser.urlencoded({
extended: true
}));
});
app.post('/submit', function (req, res) {
console.log(req.body);
});
On client side, there's a form which is handled with Angular controller:
$scope.submit = function () {
// $http.post('/submit', $scope.data); // POST request to send data to the server
$http({
method: 'POST',
url: '/submit',
data: $scope.data
});
console.log('POST /submit ' + JSON.stringify($scope.data));
};
In browser's console everything is fine: $scope.data is valid; Node.js also responds with console.log, as expected, but writes undefined which means that, well, request.body is undefined.
What do I do wrong? How can I fix it?
If you're using Express 3 you shouldn't have to use the body-parser module as it is already bundled with Express 3 as express.bodyParser. You're getting an empty body because you're putting app.use(app.router) before the body parser.
app.configure(function() {
app.use(express.bodyParser());
app.use(app.router);
});
Which is why your other solution is working:
app.post('/submit', bodyParser.json(), function (req, res) {
Well, I just came up with solution, and it works. Here the app.post using body-parser is explained in few words. So I changed POST request handler definition to:
app.post('/submit', bodyParser.json(), function (req, res) {
console.log(req.body);
});
And now not only console.log(req.body) returns valid data, but it's deserialized into JSON correctly on the server without any extra code (which is, well, expected from Angular+Node pair).

Nodejs not receiving POST body

I'm sending a POST in angularjs like so:
$http.post("/mypath", { data: "foobar" })
And in nodejs (expressjs) I'm trying to pick it up like so:
app.post "/mypath", (req, res) ->
console.log "req.body: ", req.body
res.end()
I've tried various different incarnations (body: "foobar", etc), but I keep getting req.body: undefined
Is there a simple way to read the payload in node/express?
To get data from a POST in Node, you need to use a body Parser. eg:
var bodyParser = require('body-parser');
//use bodyParser() to let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Resources