req.body empty Node.js - angularjs

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
}));

Related

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

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"});

data from my db returns partial content from my Restful API (206 partial content)...

im having a little problem with my M.E.A.N(mongo, express, angular, node) application, when i do a GET request from my node server, it displays on 10 items instead of all 21 that are in the mongo db. i did some search on google and i read stuff saying it had to do with my CORS set up on my servers side, but i still cant seem to figure it out... here's my code:
index.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
var cors = require('cors');
// Create the application.
var app = express();
//enable the use of cors
app.use(cors());
// Add Middleware necessary for REST API's
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
// CORS Support
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.models = require('./models/index');
// Load the routes.
var routes = require('./routes');
_.each(routes, function(controller, route) {
app.use(route, controller(app, route));
});
// Connect to MongoDB
var db = mongoose.connect('mongodb://localhost/isdbmeanapp');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', function() {
// Load the models.
app.models = require('./models/index');
app.listen(3000);
console.log('Server running on localhost port 3000...');
});
i currently have 21 users(dummy data) in my database(mongodb) but when i run the above restangular query, it displays only 10 users. i also tried making requests with postman and thesame thing happens (with a 206 server status code).
im using restangular to make my requests:
Restangular.all('user').getList().then(function(user){
$scope.users = user;
});
please i need help in solving this problem... thanks in advance...

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!

How do I read the length of array loaded from req.session in nodejs?

My code looks like this in my post request:
var titles = [];
movies.forEach(function(movie) {
// If title exists in array, dont push.
if(titles.indexOf(movie.title) > -1){
console.log('skipped duplicate title of '+movie.title);
}
else{
titles.push(movie.title);
console.log('pushed '+movie.title);
}
});
req.session.titles = titles;
console.log(req.session.titles);
and my get request looks like this:
app.get('/search', function(req, res) {
var arr = req.session.titles;
if(arr.length > 0) {
//do something
}
But I get the error TypeError: Cannot read property 'length' of undefined at Object
My server.js looks like this. I don't think sessions are working tho.. What am I doing wrong?
I think I had sessions working before and I have all the packages installed..
My req.session.titles is empty as thought in the comments..
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 3003;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var fs = require('fs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
//var Parse = require('../app/models/parse');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({
secret: 'hakunamatata',
resave: false,
saveUninitialized: true
}));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// set the default tmpdir for uploads (IMPORTANT)
process.env.TMPDIR = './tmp';
//load all files in models dir
fs.readdirSync(__dirname + '/app/models').forEach(function(filename) {
if (~filename.indexOf('js')) require(__dirname + '/app/models/' + filename)
});
// launch ======================================================================
app.listen(port);
I can see one error definitely in line var titles = [];
Here you actually drop title every post request. What you should do is to write
var titles = req.session.titles || [];
Also you executing app.use(cookieParser()); twice.
Don't think that fixing those two errs will fix the problem, but anyway they there.
The problem was not in my sessions but rather in the get request executing before the omdb api is done reading data to the session variable. So the session variable was not set before I tried to access it.
I used callback function to solve this.
Link to that question and how I solved it is here.

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).

Resources