Getting angularJS $http.post from nodeJS - angularjs

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

Related

How to post JSON object angularjs

I would like post object and read it on node server but I have an error.
controller :
$scope.update = function(contact) {
console.log(contact);
$http.post('/contactlist/' + contact).then(function(response) {
console.log(response);
});
};
server node :
app.post('/contactlist/:contact', function (req, res, next) {
console.log(req.body);
res.json();
});
server node head:
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = *****************
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + "/public"));
Screenshot of the error network POST :
enter image description here
server error of console.log(req.body);
[object Object]
SyntaxError: Unexpected token o in JSON at position 1
You are not passing any parameter in your post API. POST needs a parameter to be passed and since you are passing the parameter in the request URL, you can try by passing an empty object like this:
$http.post('/contactlist/' + contact,{}).then(function(response) {
console.log(response);
});
You are trying to concatenate an object in the URL which is not a good approach. If you want to still do this way, stringify it and then append it to URL. And you can get it with the help of req.query. But it is better if you change the url and pass contact as a parameter to your API call.
Problem solved by :
var OBJ = JSON.stringify(yourOBJ);
For node js there different syntax please see below:
var yourObj = {};
$http.post('/contactlist/' + contact, {data: yourObj}).then(function(response)
{
console.log(response);
});
This will work

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

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

How to pass multiple parameters in a URL Angular/REST API

I'm trying to pass multiple parameters in a URL with no luck. I'm not sure if it makes a difference but I am doing it through Angular. I'm trying to send the request to a REST API backend that I know works for single requests. Here is what my backend looks like
index.js
var express = require('express');
var router = express.Router();
var game = require('./game');
router.get('/api/v1/gameRefined/:from_datepicker:to_datepicker:from_timepicker:to_timepicker:selectLevel', game.getAllRefined);
module.exports = router;
game.js
...dbconnection stuff...
var game={
getAllRefined: function(req, res) {
var refines = req.params;
console.log("getting refined games");
pool.getConnection(function(err, connection){
var query = connection.query('SELECT * FROM game WHERE date >= ? AND date <= ? AND time >= ? AND time <= ? and level = ?', [refines.from_datepicker, refines.to_datepicker, refines.from_timepicker, refines.to_timepicker, refines.selectLevel], function(err, rows) {
connection.release();
if(err) {
throw err;
}else{
res.json(rows);
}
});
})
},
}
module.exports = game;
I send the request from this factory
.factory('gameFactory', ['$http',
function($http) {
var _gameFactory = {};
_gameFactory.getRefinedGames = function(dateFrom,dateTo,timeFrom,timeTo,level) {
var encodedParam = encodeURIComponent(baseUrl + '/api/v1/gameRefined/?from_datepicker='+dateFrom+'&to_datepicker='+dateTo+'&from_timepicker='+timeFrom+'&to_timepicker='+timeTo+'&selectLevel='+level+'');
return $http.get(encodedParam);
}
return _gameFactory;
}])
That sends this request that comes back as a 404:
http://localhost:8100/http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1%2FgameRefined%2F%3Ffrom_datepicker%3D2015-02-05%26to_datepicker%3D2015-02-19%26from_timepicker%3D12%3A00%26to_timepicker%3D18%3A00%26selectLevel%3D1
I have tried it encoded and not encoded, with forward slashs, with semi colons, but nothing has worked so far.
I don't know why a localhost gets appended at the start, but even trying it in postman without the first localhost still is a 404 error.
How should I be doing this? Any help is appreciated. Thank you.
First, other than separating the work into a factory, you aren't really using Angular here. Second, I would consider posting to your API, return JSON results from the API, and then use a promise to read the data back into Angular.
Use $http.post
Let Angular do this work for you. Something like the below will generate the URL request for you. The return value of $http is also a promise, so using .success and .error will allow you to parse any returned data as well, even if it is just a success or failure message - but it is a great method of passing data between server/API and client.
.factory('gameFactory', ['$http',
function($http) {
return {
reachAPI: function(dateFrom, dateTo) {
$http.post('http://localhost:8080/api/v1', {
'dateFrom': dateFrom,
'dateTo': dateTo
})
.success(function(data, status, headers, config) {
*things happen*
data.somethingReturned // from your API
});
}
}]);
Consider body-parser
I know you said you have confidence in your REST API structure, but body-parser is an Express middleware that can parse URL-encoded strings and may prove helpful in reading your data. Personally, I think it lends towards more readable code.
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
router.route('/api').post(function(req, res) {
*things happen*
req.body.dateFrom //find your data
*things happen*
res.json(returnedData);
});
Hope that helps

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